1
votes

I'm getting an error in my loading indicator and I don't understand why:

LoadingIndicatorComponent.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'hidden: true'. Current value: 'hidden: false'.

I've got a simple loading indicator image:

<img class="loader" [hidden]="!isLoading" src="loading.svg" alt="Loading..." />

With the following code:

export class LoadingIndicatorComponent implements OnInit {
  public isLoading = false;
  constructor(private loader: LoadingIndicatorService) {
  }

  ngOnInit() {
    this.loader.IsLoading.subscribe((value) => {
      this.isLoading = value;
    });
  }
}

Which makes use of the following service:

export class LoadingIndicatorService {
  constructor() { }

  private workload = 0;
  private _loading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  public readonly IsLoading: Observable<boolean> = this._loading.asObservable();

  public StartWork(): void {
    this.workload++;
    this._loading.next(this.workload > 0);
  }

  public EndWork(): void {
    this.workload--;
    this._loading.next(this.workload > 0);
  }
}
2
Here is an very good exploration about this problem in angular. stackoverflow.com/questions/44691745/… - Gregor Doroschenko

2 Answers

1
votes

You are modifying value of isLoading during change detection cycle that is causing issue. which is this line of code

this.loader.IsLoading.subscribe((value) => {
  this.isLoading = value;
});

is loading modified by you service. so you need to put work around for this

this.loader.IsLoading.subscribe((value) => {
 Promise.resolve(null).then(() =>  this.isLoading = value);
});

answer is based on this post : Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error

0
votes

I also faced this type problem. Use this

this.loader.IsLoading.subscribe((value) => {
    setTimeout(() => this.isLoading = value, 0)
});