相关疑难解决方法(0)

markForCheck()和detectChanges()之间有什么区别

ChangeDetectorRef.markForCheck()和之间有什么区别ChangeDetectorRef.detectChanges()

我只在SO上找到了关于NgZone.run()这两个函数之间的差异的信息,但不是这两个函数之间的区别.

对于仅提及文档的答案,请说明一些实际场景,以选择其中一个.

angular2-changedetection angular

146
推荐指数
4
解决办法
5万
查看次数

为什么我需要添加 markForCheck() 来触发 Angular 中的更改检测?

我不太明白为什么我需要在下面的代码中添加 markForCheck() 以使更改可见。为什么我的@Input() 没有触发变化检测?

我正在将我的项目重构为 OnPush。这两个组件都启用了 OnPush。据我了解,当启用此功能并且 Input() 更改(例如messages)时,更改检测将被触发。

在下面的代码中,我通过graphqlService. 当我收到调用时,我会对传入的数据进行一些解析,然后将其设置为informationMessages属性,该属性cv-messages通过其messages属性绑定到子组件。

结果是该ngOnChanges函数仅在informationMessages属性初始化时被调用一次。但不是当最终解析的数据设置为它时。

如果我添加 markForCheck() 它工作正常。

考虑这个父组件,它有一个这样的模板:

<cv-messages [messages]="informationMessages"></cv-messages>
Run Code Online (Sandbox Code Playgroud)

以及带有这段代码的打字稿文件:

informationMessages: InformationMessageType[] = [];

ngOnInit() {
    this.graphqlService.loadInformationMessages().subscribe(data => {
        const informationMessages: InformationMessageType[] = data;

        .... // parsing stuff

        this.informationMessages = informationMessages;
        // add markForCheck() here
    });
}
Run Code Online (Sandbox Code Playgroud)

消息组件有一个 ngOnChanges 函数,如下所示:

ngOnChanges(changes) {
    console.log(this.constructor.name ' CHANGE:', changes);
}
Run Code Online (Sandbox Code Playgroud)

更新:

您可以在以下答案的评论中找到解决方案。基本上,当异步更改时不会触发更改检测@Input()。所以在这种情况下,我们需要添加一个markForCheck()来强制更改检测。

data-binding angular2-changedetection angular

4
推荐指数
1
解决办法
1652
查看次数