使用 Angular 组件时出现 ExpressionChangedAfterItHasBeenCheck 错误

ExpressionChangedAfterItHasBeenCheck Error in using Angular Component

我在我的 Angular 应用程序中创建了一个日期选择器组件。当我在 *ngIf 中使用它时,出现错误 ExpressionChangedAfterItHasBeenCheck。 让我使用两个组件 P 和 C。 P 作为父输入字段。

<INPUT [p]=" '' ">

C 作为子下拉列表附加在 INPUT 之后。

<DIV>
// drop-down code
</DIV>

当在 *ngIf 中动态创建 P 时,出现这样的错误 ExpressionChangedAfterItHasBeenCheck。

一个运行宁Angular应用程序是一个组件树。在更改检测期间,Angular 对每个组件执行检查,其中包含按指定顺序执行的以下操作:

  1. 更新所有 child components/directives
  2. 的绑定属性
  3. 在所有 child 上调用 ngOnInit、OnChanges 和 ngDoCheck 生命周期挂钩 components/directives
  4. 为当前组件更新DOM
  5. 运行 child 组件的更改检测
  6. 为所有 child 调用 ngAfterViewInit 生命周期钩子 components/directives

每次操作后 Angular 记住它用于执行操作的值。它们存储在组件视图的 oldValues 属性 中。对所有组件完成检查后 Angular.

所以最后,我们需要让它与 Angular 同步,为了解决这个问题,我们使用 setTimeout inside lifecycle hooks.

ngOnInit() {
    setTimeout(() => {
    // Your Code
    });
}
ngAfterViewInit() {
    setTimeout(() => {
    // Your Code
    });
}