Many Angular developers face this common Error NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. There is no need to worry about we you are at the correct place to find its solution. We faced the same error and received the below error message in the console.
When Error “ERROR: NG0100 OR ExpressionChangedAfterItHasBeenCheckedError” Occurs?
Error Situation: Changing Variable Value After View Init
When we have initialized variable values and we try to change them after a view is initialized using the ngAfterViewInit method OR ngOnChange, this error appears in the browser’s console.
Code Causing the Error
Now we know when the Error NG0100 occurs. Let’s understand with the code.
Here, I have used a variable “title” to display dynamic content. The value of that variable comes from app.component.ts file
In this file, we can see that the title variable is undefined initially and initiated after view initialization using ngAfterViewInit.
Solution for Error NG0100
As we know the Error NG0100 occurs due to a change in variable value after view initialization in Angular. The solution is simple we have to initialize values for all variables on view initialization. There are two methods to initialize values on view initialization.
- Using Constructor
- Using ngOnInit
Method 1: Solve NG0100 Using Constructor
Angular constructor helps to initialize variables before view initializes. We can see the correct implementation to use Angular constructor to solve the “ng0100:Expression Changed After It Has Been Checked Error” in the below screenshot.
Method 2: Solve NG0100 Using OnInit
Angular OnInit helps to initialize variables when view initialization starts in Angular. Also, Angular processes all the mentioned procedures inside “OnInit” before view initialization completes. We can see the correct implementation to use Angular OnInit to solve the “ng0100:Expression Changed After It Has Been Checked Error” in the below screenshot.
Output After Solution Applied
We can choose any method mentioned above. The output will be the same and you will see no error message of NG0100 or Expression has changed after it was checked. In our example, the console output will be as the below screenshot.
I hope now you have a complete understanding of “Error NG0100” and “Error: Expression has changed after it was checked”, how this error occurs and the complete solution with an easy approach.
Happy Coding 🙂