Search code examples
angularangular-reactive-formsangular-forms

ExpressionChangedAfterItHasBeenCheckedError Updating Validator of Sub-Form from Parent


I've created a few reactive sub-forms that I've connected to the parent form group using the FormGroupDirective, but when I update a sub-forms validators from the parent in ngAfterViewInit when the controls have been added, and invoke updateValueAndValidity I get this error in the console:

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

Is it possible to avoid this error? I created a StackBlitz of the issue, and you can see the error appear in the console when the application loads as I set the profile description validator and invoke updateValueAndValidity in ngAfterViewInit of the PageComponent.


Solution

  • You could run change detection in your hook:

    import { ChangeDetectorRef } from '@angular/core';
    
    constructor(private changeDetector: ChangeDetectorRef) { }
    
    public ngAfterViewInit() {
      ...
      this.changeDetector.detectChanges();
    }
    

    Or use onPush change detection:

    import { ..., ChangeDetectionStrategy } from '@angular/core';
    
    @Component({
      ...
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    

    This will make sure change detection runs only by comparing references instead of when mutating.