ExpressionChangedAfterItHasBeenCheckedError is one of the most common errors encountered by developers who are working in Angular.
This error is thrown in development mode.
Let’s look at the common causes of this error.
One of the reasons could be that the code is being executed in AfterViewInit
. When a user works with ViewChild
, this error is very common.
The developer may be making changes directly in the DOM
using jQuery. Most of the time, Angular may not be able to render according to these changes.
A function is being called from the HTML template itself.
A quick fix involves using setTimeout
(it will cause Angular to check the whole application for changes) or ChangeDetectorRef
(the component view and its children are checked).
Since the changes are not being detected, you may move the code from ngAfterViewInit
to OnInit
, given that our code is not fully dependent on ViewChild
. This will allow angular to render changes in the DOM
.
You can disable automatic change detection in your component and tell Angular yourself when it should detect changes. The ChangeDetectionStrategy
can be specified to OnPush
.
Check to see if you have modified a component’s @Input
properties directly in the component itself as this could cause the error. In this case, the parent component can be used to update the @Input
properly.
Free Resources