Lazy Load Routes in Angular

Paul Halliday
InstructorPaul Halliday
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Instead of including modules as part of your main app bundle, load them on demand using loadChildren within the Angular Router.

This enables you to have a smaller bundle size and better performance as the module(s) are only loaded when required.

Instructor: [00:00] Here we have a brand-new Angular project generated with the Angular CLI. We have the app routing module, which simply has zero routes at this point.

[00:11] In order to lazy load another route, we'll start off by generating using the Angular CLI NG generate module. We'll call this the about module. We'll also add --routing. This will also generate a routing module for this feature.

[00:31] We can then generate using the NG GC about/about. This will be the about component inside of the about module. If we look inside of our about.module.ts, we can now see that we have this about component.

[00:49] Inside of our about routing module, we need to list that as the default path. We'll set the path to be the empty string and the component to be the about component.

[01:04] We can then tell our main app routing module, we can then say inside of our main app routing module that whenever we have the path about, we want to load the children of the ./about/about.module and then use the # to say the about module name.

[01:28] That will be the about module. That has to represent the class of whatever the module is that you're lazy loading. To prove this, we can open up our file system. We can see that ./about/about.module maps to this same class about module.

[01:48] Finally, if we then add in router outlet inside of our project, we should then be able to navigate using the router link to the about page. If we keep an eye on our network tab at the same time and select about, you can see that we load this about.module.gs. We're therefore only lazy loading this module when the user selects it.

egghead
egghead
~ just now

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today