在 Angular 中使用 changeDetection.markForCheck() 的正确方法是什么?

What is the right way to use changeDetection.markForCheck() in Angular?

我正在使用 markForCheck 来检测我的 angular 组件(其中有 changeDetection: ChangeDetectionStrategy.OnPush)的变化,最初,我将 markForCheck 放在函数的开头它对我有用,然后我意识到在完成所有功能操作后放置它会更有意义。

在这两种方法中,angular 都在检测最初调用或操作完成后调用的变化。

那么,如果有人可以证明使用 markForCheck 的正确方法是什么?

functionName() { // It works at both places
  this.cd.markForCheck();
  //
  .... Some Code that needs markForCheck ....
  //
  this.cd.markForCheck();
}

你需要在更改一些数据和组件后使用 this.cdr.markForCheck() 属性 changeDetection: ChangeDetectionStrategy.OnPush

因为在这种情况下组件不会重新加载自身 html 模板 如果某些子组件具有 OnPush - 父“markForCheck()”也会重绘它们。 如果在没有 OnPush 的情况下在子组件中更改数据显示,你不能使用“markForCheck()”

在我的例子中,compA 在 html 中有 mat-table,所以在重新加载项目后我调用 markForCheck() 重绘 mat-table

您使用 markForCheck() 告诉 Angular 到 'flag' 在主动更改检测策略之外发生的更改。

当您使用默认更改检测策略时,markForCheck() 不是必需的,我猜这就是为什么您最初在哪里进行 markForCheck() 调用并不重要。

调用 markForCheck() 的正确位置是在具有 ChangeDetectionStrategy.OnPush 的组件内 您做出的更改不会被 OnPush 更改接收检测.

这里有一个更深入的解释,您可能会觉得有用,

编辑:我错误地说 markForCheck() 触发了变化检测,这是不正确的。谢谢@Fatih Ersoy