0

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.

mtpultz
  • 17,267
  • 22
  • 122
  • 201

1 Answers1

1

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.

Lucas
  • 9,871
  • 5
  • 42
  • 52
  • Thanks that works, but I'm not sure what you mean by mutating? I know how change detection works, and how OnPush only updates the child if the input bindings change, but don't know what you mean by mutating. – mtpultz Sep 27 '19 at 02:25