Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Lazy Load Routes in Angular

    Paul HallidayPaul Halliday

    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.



    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




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.