ExpressionChangedAfterItHasBeenCheckedError Explained
This error indicates a real problem in your application, therefore it makes sense to throw an exception.
In devMode
change detection adds an additional turn after every regular change detection run to check if the model has changed.
If the model has changed between the regular and the additional change detection turn, this indicates that either
- change detection itself has caused a change
- a method or getter returns a different value every time it is called
which are both bad, because it is not clear how to proceed because the model might never stabilize.
If Angular runs change detection until the model stabilizes, it might run forever. If Angular doesn't run change detection, then the view might not reflect the current state of the model.
See also What is difference between production and development mode in Angular2?
I had a similar issue. Looking at the lifecycle hooks documentation, I changed ngAfterViewInit
to ngAfterContentInit
and it worked.
A lot of understanding came once I understood the Angular Lifecycle Hooks and their relationship with change detection.
I was trying to get Angular to update a global flag bound to the *ngIf
of an element, and I was trying to change that flag inside of the ngOnInit()
life cycle hook of another component.
According to the documentation, this method is called after Angular has already detected changes:
Called once, after the first ngOnChanges().
So updating the flag inside of ngOnChanges()
won't initiate change detection. Then, once change detection has naturally triggered again, the flag's value has changed and the error is thrown.
In my case, I changed this:
constructor(private globalEventsService: GlobalEventsService) {
}
ngOnInit() {
this.globalEventsService.showCheckoutHeader = true;
}
To this:
constructor(private globalEventsService: GlobalEventsService) {
this.globalEventsService.showCheckoutHeader = true;
}
ngOnInit() {
}
and it fixed the problem :)