Sub topic 5
Lazy loading a feature area with loadChildren
This chapter assumes you can write a standalone Angular component, define routes with provideRouter, read TypeScript import and export statements, and run ng build. Earlier chapters showed that a dynamic import() creates a separate chunk, and that loadComponent lazy loads one component. Here you apply the same idea to a whole feature area: a group of routes that load together.
What loadChildren does
loadChildren is a property on a route. Its value is a function that returns a promise of the child routes. The router does not call that function when the app starts. It calls it the first time a navigation matches the route's path. At that point the browser downloads the chunk, the router reads the child Routes array, and matching continues into those children.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];Three facts explain most of the behavior:
- The route
pathis a prefix. The URL/admin/usersmatchesadminin the parent, and the router then matchesusersagainst the loaded child routes. - The loaded routes are cached. The second visit to
/admindoes not download anything again. - A route with
loadChildrenhas nocomponent. It only groups routes. If you want a shared layout for the feature, put a component on a route inside the child array (shown later).
Anatomy of a lazy feature
The feature exports a plain Routes array. It does not need an NgModule. Child paths are relative to the parent prefix.
import { Routes } from '@angular/router';
import { AdminShellComponent } from './admin-shell.component';
import { AdminDashboardComponent } from './admin-dashboard.component';
export const ADMIN_ROUTES: Routes = [
{
path: '',
component: AdminShellComponent,
children: [
{ path: '', component: AdminDashboardComponent },
{
path: 'users',
loadComponent: () =>
import('./admin-users.component').then(m => m.AdminUsersComponent),
},
],
},
];The routes work like this:
/adminrendersAdminShellComponentwithAdminDashboardComponentin its outlet. The shell template contains its own<router-outlet />./admin/usersrenders the shell withAdminUsersComponent.AdminUsersComponentsits behind a second dynamic import, so it becomes a separate, smaller chunk. This is optional. Use it when one page in the feature is heavy and rarely visited.
Links to the feature should be absolute (/admin/users) when written outside the feature. Inside the feature, relative links also work, because the router tracks where each route sits in the tree.
The sequence below shows what happens on the first visit.
Converting an eager feature to a lazy one
Suppose the app currently lists the feature routes directly in the root config.
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin/admin-dashboard.component';
import { AdminUsersComponent } from './admin/admin-users.component';
export const routes: Routes = [
{
path: 'admin',
children: [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
],
},
];The two static import lines at the top pull both components, and everything they import, into the main bundle. To convert:
- Move the
childrenarray into a new file,admin/admin.routes.ts, and export it asADMIN_ROUTES. Move the component imports with it. - In the root config, replace
childrenwithloadChildrenand a dynamicimport(). - Delete the static imports of the feature's components from the root file.
- Search the rest of the eager code for other imports from
./admin/. One leftover static import is enough to keep that file in the main bundle.
The root file then matches the first example in this chapter. The URLs do not change, so links, bookmarks, and guards written against paths keep working.
Default exports
If the feature file has a single default export, you can skip the .then(...) step.
// admin/admin.routes.ts
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin-dashboard.component';
export default [
{ path: '', component: AdminDashboardComponent },
] satisfies Routes;// app.routes.ts
import { Routes } from '@angular/router';
export const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.routes') },
];The router looks for a default export on the loaded module when no .then is supplied. Use whichever style your team prefers, but keep one style across the project. Named exports make search and refactoring easier, because the symbol name is greppable.
loadChildren and loadComponent compared
| Aspect | `loadComponent` | `loadChildren` |
|---|---|---|
| Loads | One standalone component | A `Routes` array (or an NgModule) |
| Typical use | A single heavy page | A feature with several pages |
| Child routes | None from the load itself | Defined in the loaded file |
| Shared providers | Not a natural fit | `providers` on a route in the loaded array |
| Router events | No config-load events | `RouteConfigLoadStart` and `RouteConfigLoadEnd` |
Prefer loadChildren when pages in a feature share a layout, a guard, or services, because they download once and you configure them in one place. Prefer loadComponent for a lone page. Nesting them, as in ADMIN_ROUTES above, is normal.
Nested lazy areas
A lazy routes array can itself contain loadChildren. Each level creates its own chunk, and each level downloads only when the user reaches it.
import { Routes } from '@angular/router';
export const ADMIN_ROUTES: Routes = [
{
path: 'reports',
loadChildren: () =>
import('./reports/reports.routes').then(m => m.REPORT_ROUTES),
},
];Visiting /admin/reports downloads the admin chunk first, then the reports chunk. These requests run one after the other, because the router cannot know about reports until the admin routes are loaded. Deep nesting therefore adds a chain of network round trips. Two levels is usually enough. Preloading, covered in a later chapter, hides most of this cost.
Showing progress while a chunk loads
On a slow connection the user clicks a link and nothing happens until the chunk arrives. The router emits RouteConfigLoadStart and RouteConfigLoadEnd around each loadChildren download, so you can show an indicator.
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
NavigationCancel,
NavigationEnd,
NavigationError,
RouteConfigLoadEnd,
RouteConfigLoadStart,
Router,
RouterOutlet,
} from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
template: `
@if (loadingChunk()) {
<p>Loading…</p>
}
<router-outlet />
`,
})
export class AppComponent {
protected readonly loadingChunk = signal(false);
constructor() {
inject(Router)
.events.pipe(takeUntilDestroyed())
.subscribe(event => {
if (event instanceof RouteConfigLoadStart) {
this.loadingChunk.set(true);
} else if (
event instanceof RouteConfigLoadEnd ||
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
this.loadingChunk.set(false);
}
});
}
}The code also clears the flag on navigation end, cancel, and error. If the download fails, RouteConfigLoadEnd may never fire, and without those extra checks the indicator would stay on screen.
Failure modes
- The chunk fails to download. The promise rejects, and the navigation ends with a
NavigationError. The URL does not change and the user stays on the current page. Because the failed load is not cached as a success, the router tries again on the next navigation to that path. A common cause in production is a new deployment that removed the old chunk files while a user still has the old app open. Handle this with a navigation error handler (withNavigationErrorHandlerinprovideRouter) that shows a message or reloads the page. - The path never matches. If the child array lacks a route for the remaining URL segments, the router reports that it cannot match the URL, but only after the chunk has been downloaded. Always include a
''route or a**route in a feature that users can reach through its prefix alone. - The feature stays in the main bundle. Any static import of a file from the feature in eagerly loaded code defeats the split. The build still succeeds, so the mistake is silent. The chunk check in a later chapter catches it.
Putting it together
A realistic root config combines eager pages, a lazy single page, and a lazy feature area.
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{
path: 'settings',
loadComponent: () =>
import('./settings/settings.component').then(m => m.SettingsComponent),
},
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
{ path: '**', redirectTo: '' },
];Keep the landing page eager so the first screen renders without a second request. Make rarely visited or role-restricted areas lazy. A feature that nearly every user opens within seconds of the first load gains little from lazy loading, because the extra request only delays the user.
Exercise
A root route is declared as { path: 'shop', loadChildren: () => import('./shop/shop.routes').then(m => m.SHOP_ROUTES) }. The shop feature defines { path: 'cart', component: CartComponent }. What URL shows the cart, and when is the shop chunk downloaded?
Show answer
The URL is /shop/cart. The shop prefix comes from the parent route and cart from the child array. The chunk is downloaded the first time a navigation matches the shop prefix, for example when the user first goes to /shop/cart or /shop. It is cached for later visits.
Exercise
After converting a feature to loadChildren, the build output shows no new lazy chunk for it. The root routes file uses loadChildren with import() correctly. Name a likely cause and how you would find it.
Show answer
Some eagerly loaded file still has a static import from the feature folder, such as a component, service, or barrel file, so the bundler keeps that code in the main bundle. Search the non-lazy code for imports from the feature's path (for example grep -r "admin/" src/app) and remove or move them, then rebuild and check for the lazy chunk.