Lazy-loading can dramatically improve the performance of your Angular 2 application by loading content only when the user requests it. This is a simple example of lazy-loading using angular-cli.

April 30, 3017: Updated for latest @angular/cli.

You will need a recent version of node/npm and the angular-cli tool installed globally. See https://cli.angular.io/.

Create the App

Create the application scaffolding with:

Shell

1

ng new--routing trueangular-cli-lazyload

Create a “home” component that will be the default (not lazy-loaded) route:

Shell

1

nggcomponent Home

Add the Lazy-Loaded Content

Add the module to be lazy-loaded with:

Shell

1

nggmodule--routing trueLazy

Add a component to be used as the router outlet for the lazy-loaded pages:

Shell

1

nggcomponent--flat lazy

Adding the --flat option here is a matter of structural preference. I like to put the “container” component source with the module declaration so it mirrors the main app module’s structure, but you can opt to place it in a subdirectory if you like.

Finally, add a lazy-loaded “page” component to the lazy module:

Shell

1

nggcomponent lazy/LazyPage

Edit the src/app/lazy/lazy-routing.module.ts file and add the routes to be lazy-loaded:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import{NgModule}from'@angular/core';

import{Routes,RouterModule}from'@angular/router';

import{LazyComponent}from'./lazy.component';

import{LazyPageComponent}from'./lazy-page/lazy-page.component';

const routes:Routes=[

{

path:'',

component:LazyComponent,

children:[

{

path:'lazypage',

component:LazyPageComponent

}

]

}

];

@NgModule({

imports:[RouterModule.forChild(routes)],

exports:[RouterModule]

})

exportclassLazyRoutingModule{}

Edit the src/app/lazy/lazy.component.html file and add the router outlet:

XHTML

1

2

3

<h2>Lazy Module</h2>

<router-outlet></router-outlet>

Update Application Routing

Edit the file src/app/app-routing.module.ts and add the default home page and lazy-loaded routes:

Beware that when you use lazy loading, you may end up with multiple instances of your services, which may not be what you intend. This video goes into detail on two strategies for solving this problem:https://youtu.be/8VLYjt81-fE

Also, if you are like me and had to do some refactoring to solve for the multiple singletons issue and are wondering why your routerLink elements aren’t working anymore, make sure you’ve imported RouterModule into whatever module has your components using routerLink.

You don’t really need to do anything special to enable it. Check out the github. The key is to put the content you want to lazy load into its own module (see src/app/lazy) and then use “loadChildren” in the router config to load it (see app-routing.module.ts).