[Angular] How to show global loading spinner for application between page navigation
app.component.ts:
import { Component, OnInit } from "@angular/core"; import { select, Store } from "@ngrx/store"; import { Observable } from "rxjs"; import { map } from "rxjs/operators"; import { NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router } from "@angular/router"; import { AppState } from "./reducers/index"; import { isLoggedIn, isLoggedOut } from "./auth/auth.selectors"; import { AuthActions } from "./auth/action-types"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { loading = true; constructor(private store: Store<AppState>, private router: Router) {} ngOnInit() { ...this.router.events.subscribe(event => { switch (true) { case event instanceof NavigationStart: { this.loading = true; break; } case event instanceof NavigationEnd: case event instanceof NavigationCancel: case event instanceof NavigationError: { this.loading = false; break; } default: { break; } } }); } }
<div class="spinner-container" *ngIf="loading"> <mat-spinner></mat-spinner> </div>