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

问题描述

我正在使用 markForCheck 来检测我的角度分量(其中有 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“标记”发生在主动变更检测策略之外的变更。

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

调用 markForCheck() 的正确位置是在带有 ChangeDetectionStrategy.OnPush after 的组件内,您所做的更改不会被 OnPush 更改检测检测到。

这里有一个更深入的解释,您可能会觉得有帮助, What's the difference between markForCheck() and detectChanges()

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