ExpressionChangedAfterItHasBeenCheckedError Explained

Kevin LeStarge picture Kevin LeStarge · Apr 12, 2017 · Viewed 232.6k times · Source

Please explain to me why I keep getting this error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

Obviously, I only get it in dev mode, it doesn't happen on my production build, but it's very annoying and I simply don't understand the benefits of having an error in my dev environment that won't show up on prod --probably because of my lack of understanding.

Usually, the fix is easy enough, I just wrap the error causing code in a setTimeout like this:

setTimeout(()=> {
    this.isLoading = true;
}, 0);

Or force detect changes with a constructor like this: constructor(private cd: ChangeDetectorRef) {}:

this.isLoading = true;
this.cd.detectChanges();

But why do I constantly run into this error? I want to understand it so I can avoid these hacky fixes in the future.

Answer

onlyme picture onlyme · Jul 27, 2017

I had a similar issue. Looking at the lifecycle hooks documentation, I changed ngAfterViewInit to ngAfterContentInit and it worked.