Routing Angular Applications: Lesson 15 of 23

Lazy Loading

Up Next

Data and Resolve

Autoplaying in 7 seconds!

Cancel

L

Table of Contents

    azy loading is one of the best features of the router.

    There are three steps to switch a section of our site to be lazy loaded:

    • Add the route to top level routing (app.routing.ts) and set loadChildren
    • Remove the word about from about.routing.ts
    • Remove the AboutModule from main module imports

    app.routing.ts

    ...
    
      {
        path: 'about',
        loadChildren: 'app/about/about.module#AboutModule'
      },
    
    ...

    about.routing.ts

    import { ModuleWithProviders } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { AboutComponent } from './about.component';
    import { AboutUserComponent } from './about-user.component';
    import { AboutSectionComponent } from './about-section.component';
    
    const aboutRoutes: Routes = [
      {
        path: '',
        component: AboutSectionComponent,
        children: [
          {
            path: '',
            component: AboutComponent
          },
          {
            path: ':username',
            component: AboutUserComponent
          }
        ]
      }
    ];
    
    export const aboutRouting: ModuleWithProviders = RouterModule.forChild(aboutRoutes);

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.