2017-08-05 66 views
2

可以说我有一个组件结构是这样的:角ngDoCheck()被调用,即使ChangeDetectionStrategy.OnPush

AppComponent 
    HeaderComponent 
    ContentComponent 
     TodosComponent 
      TodoComponent 

如果我设置HeaderComponent的changeDetectionChangeDetectionStrategy.OnPush和改变TodoComponent东西,仍然HeaderComponent的ngDoCheck()ngAfterViewChecked()ngAfterContentChecked()被触发。

我缺少什么? ngDoCheck是否被触发?如果是,如何确定组件是否被ChangeDetection检查?

+0

这取决于什么被改变,但你应该看看这两个链接,因为他们解释可能发生的细节。 https://stackoverflow.com/questions/38629828/what-is-the-difference-between-onchanges-and-docheck-in-angular-2 https://stackoverflow.com/questions/39795634/angular-2-变化检测和changedetectionstrategy-onpush。 基于这些看起来,无论您的更改检测策略如何,都会触发'ngDoCheck'。 – eminlala

+0

因此[我的回答](https://stackoverflow.com/a/45522199/2545680)有帮助吗? –

回答

2

是的,这是正确的行为。文章If you think ngDoCheck means your component is being checked — read this article详细解释了行为。这是简短的版本。

ngDoCheck被触发在组件被检查之前。这样做是为了让您执行一些自定义逻辑,然后标记组件进行检查。您知道,Angular通过对象引用跟踪@Input s,但您可以使用ngDoCheck进行自定义跟踪。下面是简单的例子:

Component({ 
    ..., 
    changeDetection: ChangeDetectionStrategy.OnPush 
}) 
MyComponent { 
    @Input() items; 
    prevLength; 
    constructor(cd: ChangeDetectorRef) {} 

    ngOnInit() { 
     this.prevLength = this.items.length; 
    } 

    ngDoCheck() { 
     if (this.items.length !== this.prevLength) { 
     this.cd.markForCheck(); 
     } 
    } 

请记住,ngDoCheck触发仅适用于战略OnPush顶级组件。它不会触发组件子组件。

此外,即使现在已完成检查,组件也会触发ngAfterViewChecked。这也是设计。

我强烈建议您阅读Everything you need to know about change detection in Angular,特别是Exploring the implications部分。它显示您正在查找的操作顺序。

也读取Why do we need ngDoCheck

+0

但如何确定它是否实际检查,我的changeDetectionStrategy工作正常? – Mick

+0

对不起,我不明白。只有当@ @输入变化时,你的组件才会被检查。为什么你需要知道该组件已被检查。另外我强烈建议阅读文章了解过程 –

+0

是的,但没有可能确认它没有被检查?我只能知道但不确定。我读了很多文章,我很确定这是如何工作的,以及哪些事件触发了CD。我只是寻找一种方法来验证组件是否已经通过CD运行或没有。 – Mick

相关问题