本文介绍了即使使用ChangeDetectionStrategy.OnPush也会调用Angular ngDoCheck()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个像这样的组件结构:

Lets say i have a component structure like this:

AppComponent
    HeaderComponent
    ContentComponent
        TodosComponent
            TodoComponent

如果我将HeaderComponent的changeDetection设置为ChangeDetectionStrategy.OnPush并更改TodoComponent中的某些内容,则仍会触发HeaderComponent的ngDoCheck()ngAfterViewChecked()ngAfterContentChecked().

If I set HeaderComponent's changeDetection to ChangeDetectionStrategy.OnPush and change something in TodoComponent, still HeaderComponent's ngDoCheck(), ngAfterViewChecked() and ngAfterContentChecked() gets triggered.

我想念什么? ngDoCheck是否会被触发?如果是,如何确定组件是否已通过ChangeDetection检查?

What am I missing? Does ngDoCheck gets triggered anyway? If yes, how to determine if a component was checked by ChangeDetection?

推荐答案

是的,这是正确的行为.文章如果您认为ngDoCheck表示正在检查您的组件,请阅读此文章,其中详细介绍了该行为.这是简短的版本.

Yes, that's the correct behavior. The article If you think ngDoCheck means your component is being checked — read this article explains the behavior in great details. Here is the short version.

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

The ngDoCheck is triggered before the component is being checked. This is done to allow you to perform some custom logic and then mark the component for a check. You know that Angular tracks @Inputs by object references but you can use ngDoCheck to make your custom tracking. Here is the simple example:

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();
      }
   }

请记住,只有使用策略OnPush的顶级组件才会触发ngDoCheck.不会触发此子组件.

Please bear in mind that ngDoCheck is triggered only for the top level component with the strategy OnPush. It's not triggered for this components children.

即使现在已经完成检查,也将为该组件触发ngAfterViewChecked是正确的.这也是设计使然.

Also it is correct that ngAfterViewChecked will be triggered for the component even if now checking was done. This is by design as well.

我强烈建议您阅读您需要了解有关Angular中变化检测的所有信息,尤其是Exploring the implications部分.它显示了您要查找的操作顺序.

I highly recommend you to read Everything you need to know about change detection in Angular, specifically Exploring the implications section. It shows the order of operations you're looking for.

也请阅读为什么需要ngDoCheck .

这篇关于即使使用ChangeDetectionStrategy.OnPush也会调用Angular ngDoCheck()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 00:21