Sub topic 10
Lazy Loading NgModules in Older Applications
What this chapter assumes
This chapter assumes you have read the earlier chapters on loadComponent and loadChildren with a Routes array. You should also know what an NgModule is: a class decorated with @NgModule that lists declarations, imports, exports, and providers.
Many production Angular applications were written before standalone components existed (Angular 14 introduced them, and they became the default in Angular 17). Those applications use modules for everything, including lazy loading. You may need to maintain one, extend it, or migrate it. The router mechanism is the same one you have already seen. Only the unit that gets loaded changes.
Why the module is the lazy unit
In a module-based app, a component cannot compile on its own. It must be declared in exactly one NgModule, and that module's imports decide which directives, pipes, and components its templates can use. A feature area therefore ships as a module and everything that module declares.
When the router lazy loads a feature, it loads the feature module. The module's file becomes the root of a new chunk, and the bundler pulls in everything reachable only through that file. The router then instantiates the module and reads its routes.
The sequence is:
- The user navigates to a URL that matches a route with
loadChildren. - The router calls the loader function. The dynamic
import()inside it downloads the chunk. - The router takes the module class from the loaded file.
- Angular creates an injector for that module.
- The router collects the routes the module registered with
RouterModule.forChildand matches the rest of the URL against them.
The root side: loadChildren returns the module
The parent route points at the module with a dynamic import() and picks the module class out of the loaded file:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'legacy',
loadChildren: () =>
import('./legacy/legacy.module').then(m => m.LegacyModule),
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}RouterModule.forRoot is called once, in the root routing module. It creates the router service and registers the top-level routes.
Older tutorials show a string form such as loadChildren: './legacy/legacy.module#LegacyModule'. Angular deprecated that syntax in version 8 and has since removed it. If you find it in a codebase, rewrite it to the import() form above. The function form also gives TypeScript a chance to check the module path and class name.
The feature side: forChild
The lazy module declares its own routes with RouterModule.forChild. This registers routes without creating a second router.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { OrdersComponent } from './orders.component';
import { OrderDetailComponent } from './order-detail.component';
const routes: Routes = [
{ path: '', redirectTo: 'orders', pathMatch: 'full' },
{ path: 'orders', component: OrdersComponent },
{ path: 'orders/:id', component: OrderDetailComponent },
];
@NgModule({
declarations: [OrdersComponent, OrderDetailComponent],
imports: [CommonModule, RouterModule.forChild(routes)],
})
export class LegacyModule {}The paths in forChild are relative to the parent's path. With the parent route legacy, the URL /legacy/orders/42 reaches OrderDetailComponent. The empty path '' redirects to orders so that /legacy has a landing page.
Many projects split this into legacy-routing.module.ts and legacy.module.ts, as the CLI generates with ng generate module legacy --routing. The effect is identical. The routing module holds the forChild call and the feature module imports it.
Providers and injectors in a lazy module
A lazily loaded module gets its own injector, a child of the root injector. Anything listed in the module's providers array, or in the providers of modules it imports, is registered there and created when the module loads.
import { Injectable, NgModule } from '@angular/core';
@Injectable()
export class OrderCacheService {
readonly seen = new Set<string>();
}
@NgModule({
providers: [OrderCacheService],
})
export class LegacyModule {}This has three consequences:
- Components in the lazy module see the lazy instance of
OrderCacheService. Code in the main bundle cannot inject it, because the root injector knows nothing about it. - The instance is shared by everything in the lazy module's tree and lives as long as the application, since Angular does not destroy a lazy module when you navigate away.
- If the same service is also provided in the root injector (for example with
providedIn: 'root'or inAppModule), two separate instances can exist. Lazy code receives the closest one.
The third point causes the most bugs. If a SharedModule lists a stateful service in its providers and both AppModule and a lazy module import SharedModule, you get two copies of that service's state. The usual fix is to remove providers from shared modules and use @Injectable({ providedIn: 'root' }) for application-wide singletons.
The following table summarises where each registration style puts a service:
| Registration | Where the instance lives | Included in |
|---|---|---|
| `@Injectable({ providedIn: 'root' })` | Root injector, one instance | Whichever chunk first needs it, or main if the root uses it |
| `providers` in `AppModule` | Root injector | Main bundle |
| `providers` in a lazy module | That module's injector | Lazy chunk |
| `providers` in a module imported by both root and lazy | Root and lazy injectors | Two instances, one per injector |
How eager imports defeat the split
The bundler only creates a separate chunk when no static import path leads to the code from the main entry point. The classic mistake in module-based apps is importing the lazy module in AppModule as well:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LegacyModule } from './legacy/legacy.module'; // static import
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, LegacyModule], // eager
bootstrap: [AppComponent],
})
export class AppModule {}Here the import statement at the top of the file creates a static dependency from the entry point to legacy.module. The bundler must include it in the main bundle, so the import() in the route no longer produces a separate chunk. The module's routes also get registered at the root, which can change which URLs match.
The same thing happens through indirect paths. If any eagerly loaded file imports a component, pipe, or service from the lazy feature folder, that file and its dependencies move back into the main bundle. Keep code shared between lazy and eager areas in a separate shared location that does not depend on the lazy feature.
Mixing modules and standalone code
You can adopt standalone APIs gradually, because the router accepts several shapes from a loader:
- A module class, as in this chapter.
- A
Routesarray, as in the standalone chapters. - A standalone component, when you use
loadComponent.
For example, a module-based app can add a new feature without creating an NgModule:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'legacy',
loadChildren: () =>
import('./legacy/legacy.module').then(m => m.LegacyModule),
},
{
path: 'reports',
loadChildren: () =>
import('./reports/reports.routes').then(m => m.REPORT_ROUTES),
},
{
path: 'about',
loadComponent: () =>
import('./about/about.component').then(m => m.AboutComponent),
},
];A standalone component can also be declared in a module's imports array, so legacy modules can use newer components. The reverse is not true: a standalone component imports other standalone pieces or modules directly, and it is never listed in declarations.
Guards, preloading, and chunk verification work the same way for module routes. PreloadAllModules and custom strategies fetch module chunks too. A canMatch guard on the parent route prevents the module chunk from downloading. The older canLoad guard did the same job but is deprecated in favour of canMatch, so prefer canMatch in code you touch.
Migrating a lazy module to standalone
Converting is optional, since module-based lazy loading is still supported. If you do convert, work from the leaves up:
- Make each component, directive, and pipe in the feature standalone. Angular ships a schematic for this:
ng generate @angular/core:standalone, which offers a "Convert all components, directives and pipes to standalone" step. - Replace the feature's
RouterModule.forChild(routes)with an exportedRoutesarray. - Change the parent's
loadChildrento resolve to that array. - Move any
providersfrom the module to aprovidersproperty on the parent route, which creates a route-level environment injector. - Delete the module once nothing references it.
Step 4 is where behaviour can change, so test any service whose instance count or lifetime matters.
Verifying that the split worked
Build the application and read the output:
ng buildA correct split lists a lazy chunk next to the initial files. The exact names and sizes vary with your Angular version, but the shape looks like this:
Initial chunk files | Names | Raw size
main.js | main | 210.45 kB
polyfills.js | polyfills | 33.10 kB
Lazy chunk files | Names | Raw size
legacy-legacy-module.js | legacy-legacy-module | 18.72 kBIf the section named lazy chunk files has no entry for your feature, or the feature's code appears inside main.js, search for a static import of the module or of something inside its folder. The network tab in the browser's developer tools gives a second check. Load the app, confirm the lazy file is absent, then navigate to /legacy and watch it download.
Common mistakes with legacy lazy modules
| Mistake | Symptom | Fix |
|---|---|---|
| Importing the lazy module in `AppModule` | No lazy chunk in the build output | Remove it from `imports` and drop the static `import` |
| Calling `forRoot` in a lazy module | Duplicate router behaviour, odd navigation | Use `forChild` |
| Wrong class name in `.then(m => m.X)` | Compile error or runtime failure when the route loads | Match the exported module class name exactly |
| Stateful service in a shared module's `providers` | State not shared between eager and lazy areas | Use `providedIn: 'root'` |
| Component declared in two modules | Compile error: declared in more than one module | Declare once and export it from a shared module |
| Leftover string `loadChildren` syntax | Build fails on current Angular | Switch to the `import()` form |
Exercise
A module-based app has a route { path: 'billing', loadChildren: () => import('./billing/billing.module').then(m => m.BillingModule) }, but ng build shows no lazy chunk for billing and the feature's code is inside main.js. Name two likely causes and how to check each.
Show answer
First, AppModule (or another eagerly loaded module) may import BillingModule in its imports array, which requires a static import statement. Search the project for billing.module and remove any static import. Second, some eagerly loaded file may import a component, pipe, or service from the billing folder, which pulls that file and its dependencies into the main bundle. Search for imports from ./billing/ or ../billing/ in files that are not part of the billing feature, and move shared code to a location that does not depend on the lazy feature.
Exercise
A lazy LegacyModule lists OrderCacheService in its providers. The root module also provides OrderCacheService. Components in the lazy module and in the main bundle show different cached data. Why, and what is the usual fix?
Show answer
Each injector creates its own instance. The lazy module has its own child injector with its own OrderCacheService, and the root injector has another one. Lazy components receive the closest (lazy) instance, and main bundle components receive the root instance. Remove the service from the lazy module's providers and register it once with @Injectable({ providedIn: 'root' }) if it should be a singleton.