ngDoCheck 的真实用例(Angular 9)

Real UseCases for ngDoCheck (Angular9)

我是 Angular 的初学者,我一直在自学 ngDoCheck 生命周期方法

According to Documentation:
Detect and act upon changes that Angular can't or won't detect on its own.

父组件:

user={
   name:"xxx"
}

update(){
  this.user.name="yyy"
}

父视图:

<button (click)="update">update</button>
<child-comp [inputprop]="user"></child-comp>

子组件

ngDoCheck(){
console.log(this.inputprop);
}

据我所知,使用此生命周期方法获取更深层次的最新变化,而ngOnChanges无法检测到更深层次的输入属性变化等级.

简而言之,ngOnChanges 将检测 属性 更改,仅 属性 的引用发生更改。

In Above Example ngDocheck lifecycle method doesn't done anything to get the latest changes of property. But instead, change detection helps to get the latest changes in deeper level

我想知道使用 ngDoCheck 生命周期方法的确切用例。

您的子组件变更检测器可能有以下策略

  1. 默认
  2. onPush

在默认策略中,CD 运行s 用于 @Input() 修饰属性的任何更改

在onPush 策略中,CD 运行s 当你传递一个新的对象(引用)给@Input 修饰的属性。

无论策略如何,以下场景CD总是运行,

  1. 单击、提交等事件被触发
  2. XHR 调用与 API
  3. 一起工作
  4. 异步 JavaScript 执行 assetTimeOut() 或 setInterval() 等函数

请记住,AngularCD 可以可视化为有向树,这意味着所有组件都可以看作树中的一个节点,并且 Angular 总是 运行s CD从根节点到树的底部。

即使在 CC-121 中触发了一个事件,Angular 也会 运行 从根组件到底部的 CD。但是,CD 的 运行ning 将在策略设置为 onPush 的节点处停止,并且您没有在 @Input 装饰属性之一中传递新对象。

所以现在您对组件的每次 CD 运行s 何时以及如何执行 ngDoCheck() 生命周期有所了解。

希望对您有所帮助。

谢谢