Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Lazy Load Routes in Angular

    Paul HallidayPaul Halliday
    angularAngular

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss