ExpressionChangedAfterItHasBeenCheckedError 从父级更新子表单的验证器

ExpressionChangedAfterItHasBeenCheckedError Updating Validator of Sub-Form from Parent

我创建了一些反应性子表单,我使用 FormGroupDirective 连接到父表单组,但是当我从 [=12= 中的父表单更新子表单验证器时] 添加控件并调用 updateValueAndValidity 我在控制台中收到此错误:

ERROR
Error: ExpressionChangedAfterItHasBeenCheckedError: 
Expression has changed after it was checked. 
Previous value: 'ng-valid: true'. Current value: 'ng-valid: false'.

是否可以避免这个错误?我创建了一个 StackBlitz 问题,您可以在应用程序加载时看到错误出现在控制台中,因为我设置了配置文件描述验证器并在 ngAfterViewInit 中调用 updateValueAndValidity 16=].

您可以 运行 更改钩子中的检测:

import { ChangeDetectorRef } from '@angular/core';

constructor(private changeDetector: ChangeDetectorRef) { }

public ngAfterViewInit() {
  ...
  this.changeDetector.detectChanges();
}

或者使用onPush变化检测:

import { ..., ChangeDetectionStrategy } from '@angular/core';

@Component({
  ...
  changeDetection: ChangeDetectionStrategy.OnPush
})

这将确保更改检测 运行 仅通过比较引用而不是在变异时进行。