Ad

How To Show Loading Component During Lazy Loading

I did lazy loading config in my angular project. That is done, But there is a problem.

because of my lazy loading component is too big (700kb), time to load component from web server is too long (0.5s)

I have to show loading component when lazy loading.

But I can not find loading option in angular router module.

I try to find angular router type definition about lazy load.

const routes: Routes = [
  { path: '', component: RandingPageComponent },
  {
    path: 'teams/:name',
    // Loading component cannot here
    loadChildren: 'src/app/domain/domain.module#DomainModule'
  },

  { path: '**', component: NotfoundComponent }
];
Ad

Answer

try this (app.component.ts)

import { Component } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event, NavigationCancel, 
NavigationError } from "@angular/router";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  public showLoadingIndicator: boolean = true;
  constructor(private _router: Router) {
    this._router.events.subscribe((routerEvent: Event) => {
      if (routerEvent instanceof NavigationStart) {
        this.showLoadingIndicator = true;
      }

      if (routerEvent instanceof NavigationEnd ||
        routerEvent instanceof NavigationCancel ||
        routerEvent instanceof NavigationError) {
        this.showLoadingIndicator = false;
      }
    });
  }
}

in html (app.component.ts)

<div *ngIf="showLoadingIndicator" class="loading">Loading&#8230;</div>
<router-outlet></router-outlet>
Ad
source: stackoverflow.com
Ad