Ameerudheen.K
Ameerudheen.K

Reputation: 667

Angular showing loader till component fully loads with data

I need to load a css loader till the components are loaded fully. so I just created a variable in component class and initialised it to true in ngOnInit liefcycle. Then I changed varibale to false on ngAfterViewInit lifecycle.

but it keeps getting me error of ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

componentLoading: boolean;

ngOnInit() {
  this.componentLoading = true;
}

ngAfterViewInit() {
  this.componentLoading = false;
}

I have saw same errors in some questions but cant understand fully on how to implement this.

The errors constructed in stackblitz https://angular-7stwmm.stackblitz.io

Upvotes: 0

Views: 1913

Answers (1)

Shadab Faiz
Shadab Faiz

Reputation: 2508

Before I give you the solution, first understand what does error ExpressionChangedAfterItHasBeenCheckedError means.

Normally, angular has something called ChangeDetectionStartegy. It is responsible for detecting any change in the property/variable values. It is through this mechanism only, that we can see the changes made in our typescript's variable reflected on our Html page. You can read in-depth about it here.

Now, during the development, this process is run twice for every change (only once in production mode). One for detecting the change and second for verifying the change. It happens in millisecond/nanosecond. During these 2 steps, if the variable/property changes its value, then angular will throw this warning. This is what is happening in your case. There are multiple ways to overcome this:

  1. Using setTimeout(easier but not recommended).

    ngAfterViewInit() {
     setTimeout(() => {
     this.componentLoading = false;
    });
    }

  1. using custom logic:

    a. Start the loader from the previous component.
    b. Stop the loader in the constructor of the current component. or if your component needs the data from service, then stop it after observables success/error event.

Upvotes: 2

Related Questions