Angular Loading Spinner Error:ExpressionChangedAfterItHasBeenCheckedError
Asked Answered
D

2

5

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?

Destroy answered 30/7, 2018 at 8:36 Comment(2)
Please provide a minimal reproducible example reproducing the issue.Ronn
A quick workaround is to use ChangeDetectorRef and call detectChangesHockey
I
7

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

Indus answered 30/7, 2018 at 9:0 Comment(0)
D
0

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'.

Delitescence answered 30/7, 2018 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.