【问题标题】:Function Not Running When Placed Within Angular's ngOnChanges Life Cycle Hook放置在 Angular ngOnChanges 生命周期钩子中时函数未运行
【发布时间】:2017-09-27 01:32:01
【问题描述】:

我正在检查以确保通过 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 设计用于的那种场景吗?我错过了什么吗?

【问题讨论】:

    标签: javascript angular lifecycle eventemitter


    【解决方案1】:

    来自文档:

    Angular 在检测到更改时调用其 ngOnChanges() 方法 组件(或指令)的输入属性。

    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

    【讨论】:

    • 啊,好吧。谢谢,@DeborahK。知道我可以在这种情况下使用什么吗?我将检查生命周期文档,看看是否有其他我可以使用的文档。
    • 您应该在事件发生时获取事件并编写代码。您不需要为此使用生命周期挂钩吗?
    • 对。这也是我最初的想法。这就是为什么我对为什么每次新事件触发要通过原始组件的输出发送的值时都没有运行这个 sortByFilters() 函数感到困惑。我得深入研究看看是否还有其他问题。
    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2017-11-22
    • 2019-06-26
    • 2017-09-16
    • 2017-03-29
    相关资源
    最近更新 更多