Igor Simic
4 years ago

How to show preloader on every route change in Angular


So, in our Angular 2+ app we want to show pre-loader on on every route change, and especially when we have to load data from backend. Just to inform user that something is happening and that page will be ready soon. In our case prerequisite for this is to have implemented route resolver. Info about how to implement route resolver you can find https://www.coditty.com/code/angular-how-to-load-data-from-backend-before-rendering-component-html-on-route-change

Solution for this is very simple, in our app component we will subscribe to route changes and every time when route change start ( NavigationStart ) or route change ends ( NavigationEnd ) we can change the value of our variable which will be used to show/hide preloader.

In our  app.component.ts we will import Router and subscribe to router event and call custom method when event happen:
import {
  NavigationCancel,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  Router,
  RouterEvent,
  RouterOutlet
} from '@angular/router';export class AppComponent {

showLoader: boolean = true;

constructor(
...
      private router: Router
){


    router.events.subscribe( (routerEvent: RouterEvent) => {

        this.checkRouteChange(routerEvent);

    });

  };
and now in our checkRouteChange method we will check what is the current event:
checkRouteChange( routerEvent:RouterEvent){

  console.log("router event");
  console.log(routerEvent);
  
  // if route change started
  if(routerEvent instanceof NavigationStart){

    this.showLoader = true;

  }
  // if route change ended
  if(routerEvent instanceof NavigationEnd ||
    routerEvent instanceof NavigationCancel ||
    routerEvent instanceof NavigationError
  ){
    this.showLoader = false;
  }

} 
and now you can use showLoader to hide or show your preloader:
<div class="my-preloader" *ngIf="showLoader"></div>