Angular NG0100: Expression has changed after it was checked – ExpressionChangedAfterItHasBeenChecked


The “ExpressionChangedAfterItHasBeenChecked” error in Angular typically occurs when there is a change in the component’s data after the initial change detection cycle has completed. This error is Angular’s way of ensuring that the application’s state remains consistent.

To resolve this error, you can follow these general steps:

  1. Identify the Issue: First, you need to identify which part of your Angular component is causing the error. Look for any code that changes data in your component after the initial rendering has occurred.
  2. Use ngAfterViewInit: If you’re changing data in your component after the initial render, consider moving that code to the ngAfterViewInit lifecycle hook. This hook is called after the initial view has been initialized, so it’s a suitable place for making changes to the component’s data.
import { Component, AfterViewInit } from "@angular/core";
@Component({
selector: "app-your-component",
templateUrl: "./your-component.component.html",
})
export class YourComponent implements AfterViewInit {
ngAfterViewInit() {
// Your code to modify data goes here
}
}
  1. Use ChangeDetectorRef: If you can’t avoid changing data after the initial render, you can manually trigger a change detection cycle using ChangeDetectorRef. Import it into your component and use it like this:
import { Component, ChangeDetectorRef } from "@angular/core";
@Component({
selector: "app-your-component",
templateUrl: "./your-component.component.html",
})
export class YourComponent {
constructor(private cdr: ChangeDetectorRef) {}
someMethodThatChangesData() {
// Your code to modify data goes here
this.cdr.detectChanges();
}
}
  1. Optimize and Refactor: In some cases, you might need to refactor your code to eliminate the need for changing data after the initial render. Consider using Angular’s built-in features like Observables, ngIf, ngFor, and ngSwitch to manage your component’s state more effectively.

Remember that the “ExpressionChangedAfterItHasBeenChecked” error can be an indication of a design issue in your application. It’s a good practice to try to structure your code in a way that minimizes these errors by following Angular’s change detection rules.

When I faced this issue I had implemented ngOnChanges on my Component which was causing this error to occur. I checked this function and added this.cdr.detectChanges() after touching the form elements in the function.