think123 think123 - 8 months ago 1925
HTML Question

Show loading screen when navigating between routes in Angular 2

How do I show a loading screen when I change a route in Angular 2?


If you know your way around in Angular2, this is what you'll need


import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';

bootstrap(MyApp, [SpinnerService]);

Root Component- (MyApp)

import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
  selector: 'my-app',
  directives: [SpinnerComponent],
  template: `
export class MyApp { }

Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)

import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
  selector: 'spinner-component',
  'template': '<div *ngIf="active" class="spinner loading"></div>'
export class SpinnerComponent {
  public active: boolean;

  public constructor(spinner: SpinnerService) {
    spinner.status.subscribe((status: boolean) => { = status;

Spinner-Service (bootstrap this service)

Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';

export class SpinnerService {
  public status: Subject<boolean> = new Subject();
  private _active: boolean = false;

  public get active(): boolean {
    return this._active;

  public set active(v: boolean) {
    this._active = v;;

  public start(): void { = true;

  public stop(): void { = false;

All Other Routes' Components


import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
   template: `<div *ngIf="!" id="container">Nothing is Loading Now</div>`
export class SampleComponent {

  constructor(public spinner: SpinnerService){} 

    this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component


If you don't, It's too much of work to setup a Demo, but I'll try to find some time and implement if someone else doesn't until that time.