Angular spinner infinite looping while ngIf in router-outlet

Viewed 417

I am creating an application with frontend in Angular with backend in Laravel.

This application includes an interceptor to display a spinner. For this, I created a service with a BehaviorSubject and an Observable like this:

export class SpinnerService {

  private loadingSubject: BehaviorSubject<boolean>;
  public loading: Observable<boolean>;

  constructor(
  ) {
    this.loadingSubject = new BehaviorSubject<boolean>( false );
    this.loading = this.loadingSubject.asObservable();
  }
  changeLoadingStatus(status: boolean) {
    this.loadingSubject.next( status );
  }
}

In component I do a subscribe in this Observable and pass the value to loading variable like this:

this.sSpinner.loading
      .pipe(delay(0)) 
      .subscribe((loading) => {
        this.loading = loading;
        console.log(loading);
      });

I put a mat-spinner next to the router-outlet and includes the *ngIf directive, like this:

<mat-card class="col-md-8 offset-md-2">
    <mat-spinner *ngIf="loading" class="loading-container flex-content-center"> </mat-spinner>
    <router-outlet> </router-outlet>
</mat-card>

That way it works, but the route-outlet and the spinner are displayed. If I place the *ngIf directive on the router-outlet with the inverse loading parameter, to hide router-outlet, like this:

<mat-card class="col-md-8 offset-md-2">
    <mat-spinner *ngIf="loading" class="loading-container flex-content-center"> </mat-spinner>
    <router-outlet *ngIf=" ! loading"> </router-outlet>
</mat-card>

The app enters an infinite loop, reloading the page until the memory overflows.

I understand that I can, through css, stylize and make the appearance beautiful without using *ngIf in the router-outlet, however, I would like to understand the reason why the app enters infinite looping in this case.

Any help will be welcome.

Thanks!

1 Answers

I realy want to know what occurs in this case, why reload occur when I put ngIf directive in the router-outlet. But by hour I use css to hide:

<mat-card class="col-md-8 offset-md-2">
  <mat-spinner *ngIf="loading" class="loading-container flex-content-center"></mat-spinner>

  <div [style.display]="loading ? 'none' : 'block'">
    <router-outlet></router-outlet>
  </div>
</mat-card>
Related