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?

SteveBl
  • 253
  • 4
  • 12

2 Answers2

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

Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
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'.

Cod3n0d3
  • 185
  • 1
  • 11