Sub topic 10
Lazy loading NgModules in older applications
This chapter assumes you know how to define routes with the Angular Router, how loadChildren works with a Routes array, and the basics of NgModules (@NgModule, declarations, imports). If you have only used standalone components, this chapter shows what you will meet in older code bases and how to migrate it.
How the older approach differs
Before standalone components, every feature area was an NgModule. A module declared its components and registered its own child routes. The router could not lazy load a bare Routes array, so loadChildren had to resolve to the module class.
The split point is still a dynamic import(). Only the thing it resolves to changes.
| Approach | `loadChildren` resolves to | Where the child routes live |
|---|---|---|
| Standalone | A `Routes` array such as `ADMIN_ROUTES` | A plain exported constant |
| NgModule | A module class such as `LegacyModule` | `RouterModule.forChild(...)` inside the module |
Configuring the parent route
The parent route points at the module file and returns the module class from the promise.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'legacy',
loadChildren: () =>
import('./legacy/legacy.module').then(m => m.LegacyModule),
},
];The .then(m => m.LegacyModule) step picks the exported class out of the loaded file. If you return the wrong export, the router fails at navigation time, not at build time.
The lazy module registers its own routes
The module uses RouterModule.forChild, never forRoot. The root module calls forRoot once because it creates the router service. A lazy module only adds routes to the existing router.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { LegacyHomeComponent } from './legacy-home.component';
const routes: Routes = [
{ path: '', component: LegacyHomeComponent },
];
@NgModule({
declarations: [LegacyHomeComponent],
imports: [CommonModule, RouterModule.forChild(routes)],
})
export class LegacyModule {}The route with path: '' here is relative to the parent's legacy path, so the page is served at /legacy.
Providers and the module injector
A lazy NgModule gets its own injector. Services listed in the module's providers array are created in that injector, so they exist only once the module has loaded. This is the older equivalent of the providers property on a route.
Two things follow from this:
- A service provided in a lazy module is separate from a same-named service provided in the root. Two instances can exist, which causes bugs that look like lost state.
- A service with
providedIn: 'root'stays in the root injector, even if only the lazy module uses it. Which chunk contains it depends on what imports it.
Common mistakes in older code
- Importing the lazy module in
AppModule. A staticimports: [LegacyModule]pulls the module into the main bundle. Theimport()still works, but no separate chunk is produced for that code. - Using
forRootin a feature module. This registers a second router service and breaks navigation. - Importing a shared module with providers. If a shared module lists services in
providers, each lazy module that imports it gets its own copy. - Referencing a lazy component from an eager file. Even a type-only use can keep the file in the main bundle if the import is not elided.
Migrating to standalone
You can mix both styles in one router configuration, so migration can go one feature at a time. A standalone parent route can lazy load an NgModule, and an NgModule route config can lazy load a Routes array. A typical migration has these steps:
- Mark the feature's components as
standalone: trueand move their dependencies into each component'simports. - Move the route array out of
RouterModule.forChildinto an exported constant. - Change
loadChildrento resolve to that constant. - Move
providersfrom the module to theprovidersproperty on the route. - Delete the empty module.
The Angular CLI offers a schematic, ng generate @angular/core:standalone, that automates much of this. Review its output, because providers placement is the part that most often needs manual attention.
Exercise
A team's AppModule lists LegacyModule in its imports array, and the app also has loadChildren: () => import('./legacy/legacy.module').then(m => m.LegacyModule). Why does the build output show no separate legacy chunk, and what is the fix?
Show answer
The static import in AppModule makes the module part of the main bundle, so the bundler has nothing to split off. Remove LegacyModule from AppModule.imports (and any other eager file that imports it) and keep only the loadChildren dynamic import.
Exercise
Which RouterModule method must a lazy feature module use to register its routes, and why is the other one wrong?
Show answer
RouterModule.forChild(routes). forRoot creates the router service and is meant to be called once in the root configuration. Calling it in a lazy module registers a second router and breaks navigation.