Keath Milligan

On software development, quality, security and broken racecars

Lazy-loading content with angular-cli

A quick example of creating a lazy-loaded module with angular-cli.

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.

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

Create the App

Create the application scaffolding with:

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

Add the Lazy-Loaded Content

Add the module to be lazy-loaded with:

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

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

Create a new file named lazy.routes.ts in src/app/lazy and add the routes to be lazy-loaded:

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

Now edit the src/app/lazy/lazy.module.ts file and integrate the routes:

Create Application Routing

Add a new file, src/app/app.routes.ts with the default and lazy-loaded routes:

Add some navigation to src/app/app.component.html:

Finally, edit the src/app/app.module.ts file. You notice that angular-cli automatically add the lazy module to its declarations. Since we want this module to be lazy-loaded, we don’t actually want that, so remove it and add the routing as follows:


Compile the app and start the angular-cli server with:

In Chrome, open the developer tools window and select the “Network” tab so you can see all of the HTTP requests being made.

Now navigate to http://localhost:4200. You see the default home page and the navigation links.

Note the requests that were made to load the app in the debugger:

Now click the “Lazy Page” link. You should see the “lazy page works” message:

In the debugger, note that an additional request was made to load “0.chunk.js” to render the lazy-loaded page:


Source code on Github.


1 Comment

  1. With Angular CLI changing constantly, this will be a solid “getting-started” resource for the beta increments most of this year. Thank you!

Leave a Reply

Your email address will not be published.


© 2017 Keath Milligan

Theme by Anders NorenUp ↑