Skip to main content

How does the loading of lazy-loaded modules work?

In Angular, lazy-loaded modules are loaded only when the user navigates to a specific route, not when the application starts.

Key points

  1. Configuring a route for lazy loading:
ts
const routes: Routes = [ { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) } ];
  • loadChildren specifies a function that dynamically imports the module through import().
  1. What happens when you navigate to the route:
  • Angular calls the loadChildren function.
  • The browser loads the module's JS file over the network.
  • An instance of the module and its components is created, and its routes and services are registered.
  1. Advantages:
  • Reduces the size of the application's main bundle.
  • Improves the application's startup time, since not all modules need to be loaded at once.
  1. Effect on the lifecycle:
  • The lifecycle hooks of the module's components (ngOnInit, ngAfterViewInit, etc.) are called only after the lazy module is loaded and rendered.
  • A lazy-loaded module is created dynamically, as if it had been created separately.

In other words, a lazy-loaded module is loaded on demand, through a dynamic import, and its components and services are initialized only when you navigate to the corresponding route.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.