Expression has changed error on Opening a Modal Popup inside a component
ExpressionChangedAfterItHasBeenCheckedError
: Expression has changed after it was checked. Previous value: 'ng-untouched: true'
. Current value: 'ng-untouched: false'
.
setTimeout
trick doesn't work for subscribing for reactive form either. The following workaround should work for me
html
<select [ngModel]="countryId" #ngModelDir="ngModel"
(ngModelChange)="fileChangeEvent($event, ngModelDir)">
ts
import { NgModel } from '@angular/forms';
...
fileChangeEvent(event: any, ngModelDir: NgModel) {
ngModelDir.control.markAsTouched();
const modalRef = this.modalService.open(MymodalComponent, {
keyboard: false,
backdrop: 'static'
});
}
You're trying to update the property values in a lifecycle hook after they have been previously checked in the parent component.
The recommended solution is to open the modal on a button click / another user triggered event, or if you need to open it after the view is initialized you can use the setTimeout() that will skip a tick
ngAfterViewInit() {
setTimeout(() => this.openPopup());
}
Working plunker : https://plnkr.co/edit/FVV7QVp620lIGJwEhN6V?p=preview
A very nice and detailed explanation about this error : https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4