简体   繁体   中英

Angular Loading Spinner Error:ExpressionChangedAfterItHasBeenCheckedError

I did a loading-spinner component in my Angular app. I placed it in the app component next to the router-outlet with *ngIf="isLoading" so i could make it visible from everywhere in the application.
'isLoading' boolean is being updated globally using ngrx's Store.
Now i've got an error saying

Error:ExpressionChangedAfterItHasBeenCheckedError: Expression had changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'

I've been reading about this error and the conclusion was: Don't change parameter value from deeper child components.
So how can make a loading-spinner without duplicate the code in my app and without causing a change detection error?

If you change the variable inside constructor or ngOnInit , this can happen. You can use a timeout to overcome this.

ngOnInit() {
    setTimeout(() => {
        this.yourVar = 'new value'
    });
}

Check following for more information

https://github.com/angular/material2/issues/11357

https://github.com/angular/angular/issues/17572

You could try to use ngAfterContentInit life cycle hook, with a setTimeout set to 0.

example:

  ngAfterContentInit() {
    setTimeout(() => console.log('Place what you want here'), 0);
  }

Don't forget export class implements AfterContentInit and Import from '@angular/core'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM