Please explain to me why I keep getting this error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Obviously,
There were interesting answers but I didn't seem to find one to match my needs, the closest being from @chittrang-mishra which refers only to one specific function and not several toggles as in my app.
I did not want to use [hidden]
to take advantage of *ngIf
not even being a part of the DOM so I found the following solution which may not be the best for all as it suppresses the error instead of correcting it, but in my case where I know the final result is correct, it seems ok for my app.
What I did was implement AfterViewChecked
, add constructor(private changeDetector : ChangeDetectorRef ) {}
and then
ngAfterViewChecked(){
this.changeDetector.detectChanges();
}
I hope this helps other as many others have helped me.
In my case, I had this problem in my spec file, while running my tests.
I had to change ngIf
to [hidden]
<app-loading *ngIf="isLoading"></app-loading>
to
<app-loading [hidden]="!isLoading"></app-loading>
The solution...services and rxjs...event emitters and property binding both use rxjs..you are better of implementing it your self, more control, easier to debug. Remember that event emitters are using rxjs. Simply, create a service and within an observable, have each component subscribe to tha observer and either pass new value or cosume value as needed
I had a similar issue. Looking at the lifecycle hooks documentation, I changed ngAfterViewInit
to ngAfterContentInit
and it worked.
I hope this helps someone coming here:
We make service calls in ngOnInit
in the following manner and use a variable displayMain
to control the Mounting of the elements to the DOM.
component.ts
displayMain: boolean;
ngOnInit() {
this.displayMain = false;
// Service Calls go here
// Service Call 1
// Service Call 2
// ...
this.displayMain = true;
}
and component.html
<div *ngIf="displayMain"> <!-- This is the Root Element -->
<!-- All the HTML Goes here -->
</div>
To anyone struggling with this. Here's a way to debug properly this error : https://blog.angular-university.io/angular-debugging/
In my case, indeed I got rid of this error using this [hidden] hack instead of *ngIf...
But the link I provided enabled me to find THE GUILTY *ngIf :)
Enjoy.