Search code examples
angularangular-routerpreloader

Angular: Show preloader when Router is activated/change


I want to create a preloader when the router-outlet is loading a component.

What I wanted is that the preloader will display first and will cover the router-outlet and then after a delay (1s) the preloader will be hidden and will show the router-outlet.

The point of preloader is to hide the router-outlet while it is loading its content like images the preloader will be shown and after a delay the images/contents are loaded.

So far what I did is that using router-outlet and its event activate

<div *ngIf="preLoader" class="loader">
  <h2>LOADER</h2>
</div>
<router-outlet (activate)="onActivate($event)"></router-outlet>

preLoader: boolean;
  onActivate(event : any) {
    this.preLoader = true;
    console.log(this.preLoader);
    setTimeout(()=>{
      this.preLoader = false;
    },1000);
  }

My preloader stackblitz demo

If there any better solution?


Solution

  • You could use a class that applies "display: hidden" to the router-outlet whilst the preloader value is true, which will hide it within the page.

    <div [class.hide-me]="!preLoader" class="loader">
      ...content to show whilst loading...
    </div>
    <router-outlet
      [class.hide-me]="preLoader"
      (activate)="onActivate($event)">
    </router-outlet>