3

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 }
];
Hichem BOUSSETTA
  • 1,627
  • 1
  • 17
  • 22
June Lee
  • 223
  • 3
  • 12

2 Answers2

3

Router.navigate method returns a promise. So you can call then() on that. Therefore what you can do is, keeping a variable called showLoadingComponent which is, in default false and when you are navigating, do this:

this.showLoadingComponent = true;
this.router.navigate(['/newComponent']).then(value => {
      this.showLoadingComponent = false;
});

In your html,

<div *ngIf="!showLoadingComponent">
    // default content
</div>
<appLoadingComponent *ngIf="showLoadingComponent"></appLoadingComponent>

This will show your loading component after you click to navigate to your lazy loading component until the lazy loading component gets loaded.

Dulanjaya Tennekoon
  • 1,727
  • 1
  • 12
  • 25
  • 1
    As you can see here https://angular.io/api/router/Router `navigate` method returns not `Observable` but `Promise`, however you used correct method to get notified - `then`. – Buczkowski May 21 '19 at 08:59
2

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>
Jalu
  • 310
  • 1
  • 11
Ghoul Ahmed
  • 4,478
  • 9
  • 23