Lazy 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

162 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.