ExpressionChangedAfterItHasBeenCheckedError Explained

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 🙂

1 thought on “ExpressionChangedAfterItHasBeenCheckedError Explained”

Leave a Comment