I have a simple alert component which I'm creating dynamically in the view. Since it's created dynamically I've set an option to automatically display the alert after it has been initialised.
Although it's working I'd like to understand why I have to manually trigger the change detection in this particular case.
Code:
export class OverlayMessageComponent implements AfterViewInit {
...
ngAfterViewInit() {
if(this.autoShow) {
this.show();
}
this.changeDetector.detectChanges();
}
...
}
Full Sample: https://plnkr.co/edit/8NvfhDvLVBd71I7DR0kW
I had to add this.changeDetector.detectChanges();
as I was getting the following error:
EXCEPTION: Expression has changed after it was checked.
I was under the impression that using AfterViewInit
helps avoiding the issue, but I think I'm assuming wrong. Is there a way to structure the code better to avoid this error?
I'd like to understand better why this error is returned. I've seen this error a few times before, and I know that some say that with a setTimeout()
or enableProdMode()
does solve the issue, but to me it seems a hacky workaround when the framework itself is notifying you that there's a problem.
detectChanges
from here https://mcmap.net/q/107848/-what-39-s-the-difference-between-markforcheck-and-detectchanges – CollagenExpressionChangedAfterItHasBeenCheckedError
error. – Lindner