首页 > 解决方案 > ExpressionChangedAfterItHasBeenCheckedError 从父更新子表单的验证器

问题描述

我已经创建了一些反应性子表单,我已经使用 连接到父表单组FormGroupDirective,但是当我在添加控件时从父表单组更新子表单验证器ngAfterViewInit并调用时,updateValueAndValidity我得到了这个错误控制台:

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

有没有可能避免这个错误?我创建了该问题的StackBlitz,当我设置配置文件描述验证器并调用updateValueAndValidity.ngAfterViewInitPageComponent

标签: angularangular-reactive-formsangular-forms

解决方案


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

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

constructor(private changeDetector: ChangeDetectorRef) { }

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

或者使用 onPush 变化检测:

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

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

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


推荐阅读