Angular course Β· Module 3: Modules

Lazy Loading - On-Demand Squads

1 min read Β·
In this lesson3

Lazy loading is a technique for loading modules only when they are needed - like dispatching squads only when the need arises.

Lazy Loading Configuration

// app-routing.module.ts
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },

  // Lazy loaded modules
  {
    path: 'samurai',
    loadChildren: () => import('./features/samurai/samurai.module')
      .then(m => m.SamuraiModule)
  },
  {
    path: 'dojo',
    loadChildren: () => import('./features/dojo/dojo.module')
      .then(m => m.DojoModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Routing in a Feature Module

// features/samurai/samurai-routing.module.ts
const routes: Routes = [
  { path: '', component: SamuraiListComponent },
  { path: ':id', component: SamuraiDetailComponent },
  { path: ':id/edit', component: SamuraiFormComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],  // forChild, not forRoot!
  exports: [RouterModule]
})
export class SamuraiRoutingModule { }

Benefits of Lazy Loading

AspectWithout Lazy LoadingWith Lazy Loading
Initial BundleEntire applicationOnly core + home
Load timeLongShort
MemoryEverything at onceOn demand
UXLong waitQuick start

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which syntax is correct for lazy loading a module?

  2. 2. What is the main benefit that lazy loading of modules provides?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the routing configuration for lazy loading the SamuraiModule module.

  • Horizontal ordering

    Arrange the start of lazy loading on a single line (up to the dynamic import):

  • Vertical ordering

    Order the stages of lazy loading a module after the user navigates to the path:

  • Click in order

    Click the elements in order to build the call: RouterModule.forChild(

Useful articles