函数不是 运行 当放置在 Angular 的 ngOnChanges 生命周期钩子中时

Function Not Running When Placed Within Angular's ngOnChanges Life Cycle Hook

我正在检查以确保通过 Angular 的自定义 Output() 和 EventEmitter() 将某些值从一个组件发送到另一个组件。它们是从我的第一个组件的视图中发送的,如下所示:

<list [results]="results" 
    (sendLanguage)="onLanguageReceived($event)"
    (sendZipcode)="onZipcodeReceived($event)">
</list>

如果我在接收值的组件中 Angular 的 ngOnInit 生命周期挂钩中的函数中控制台记录这些值,我会看到值的当前状态已成功打印到控制台。看起来像这样:

ngOnInit() {
        this.sortByFilters(this.language, this.zipcode);
        console.log(this.sortByFilters(this.language, this.zipcode));
}

完整的 sortByFilters 函数如下所示:

sortByFilters(language, zipcode) {
    this.onLanguageReceived(language);
    this.onZipcodeReceived(zipcode);
    console.log('sortByFilters: ' + 'lang ' + language, 'zip ' + zipcode);
}

但是因为我还需要在用户单击元素时查看这些值的状态,所以我将相同的接收函数放在 ngOnChanges 生命周期挂钩中:

ngOnChanges() {
        this.sortByFilters(this.language, this.zipcode);
        console.log(this.sortByFilters(this.language, this.zipcode));
}

但是,这没有按预期工作。当用户单击相关 UI 时,ngOnChanges 中的函数永远不会触发,因此控制台日志永远不会在初始 OnInit 运行 之后发生。这不正是 ngOnChanges 设计用于的场景吗?我错过了什么吗?

来自文档:

Angular calls its ngOnChanges() method whenever it detects changes to input properties of the component (or directive).

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges

ngOnChanges 仅发生在输入属性上,而不发生在输出属性上。

在这个例子中,我有一个输入和输出。输入更改通过 ngOnChanges 进行跟踪。该事件通过其点击事件进行跟踪:

export class StarComponent implements OnChanges {
    @Input() rating: number;
    starWidth: number;
    @Output() ratingClicked: EventEmitter<string> =
        new EventEmitter<string>();

    ngOnChanges(): void {
        // Convert x out of 5 starts
        // to y out of 86px width
        this.starWidth = this.rating * 86 / 5;
    }

    onClick(): void {
        this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
    }
}

我这里有完整的例子:https://github.com/DeborahK/Angular2-GettingStarted