Sub topic 10
Lazy Loading Components and Route Groups
Every component that app.routes.ts imports statically ends up in the initial JavaScript bundle. That holds even for screens most users never open. Lazy loading tells the router to fetch a component, or a whole group of routes, only when a navigation first needs it. This chapter covers loadComponent and loadChildren, how the build splits code into chunks, how to scope services to a lazy group, and the mistakes that quietly undo the savings.
This chapter assumes you can define a Routes array and register it with provideRouter, and that you understand child routes and RouterOutlet from the previous chapters. You should also know standalone components and how dynamic import() returns a Promise.
Why Lazy Loading Matters
When the browser loads an Angular app, it must download, parse, and run the initial bundle before the first screen appears. An admin area, a reporting dashboard, or a settings wizard can add hundreds of kilobytes that most visitors never use. Lazy loading moves that code into separate files, called chunks, that load on demand.
The mechanism is the standard dynamic import() expression. The Angular CLI's build tool (esbuild in current versions) sees import('./admin/admin.routes') and emits that module and everything only it depends on as a separate chunk. The router calls the import function at navigation time and waits for the Promise to resolve.
| Approach | Route property | What loads lazily | Typical use |
|---|---|---|---|
| Eager | `component` | Nothing; code is in the main bundle | Home page, frequently used screens |
| Lazy component | `loadComponent` | One standalone component and its imports | A single heavy page |
| Lazy route group | `loadChildren` | A `Routes` array and all components it references | A feature area such as `/admin` |
Lazy Loading a Single Component with loadComponent
loadComponent takes a function that returns a Promise of a standalone component class.
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, title: 'Home' },
{
path: 'reports',
title: 'Reports',
loadComponent: () =>
import('./reports/reports.component').then(m => m.ReportsComponent)
}
];// reports/reports.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-reports',
standalone: true,
template: `<h2>Reports</h2><p>Loaded on demand.</p>`
})
export class ReportsComponent {}The .then(m => m.ReportsComponent) step picks the named export out of the module object. If the component file uses export default, the router unwraps the default export for you, so you can shorten the route:
// reports/reports.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-reports',
standalone: true,
template: `<h2>Reports</h2>`
})
export default class ReportsComponent {}
// app.routes.ts entry:
// { path: 'reports', loadComponent: () => import('./reports/reports.component') }Lazy Loading a Route Group with loadChildren
loadChildren loads a Routes array. The router merges those routes in as children of the route that declared loadChildren. Use it for a feature area that has several screens.
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, title: 'Home' },
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
},
{ path: '**', component: NotFoundComponent }
];// admin/admin.routes.ts
import { Routes } from '@angular/router';
import { AdminShellComponent } from './admin-shell.component';
import { UserListComponent } from './user-list.component';
import { AuditLogComponent } from './audit-log.component';
import { AdminService } from './admin.service';
export const ADMIN_ROUTES: Routes = [
{
path: '',
component: AdminShellComponent,
providers: [AdminService],
children: [
{ path: '', redirectTo: 'users', pathMatch: 'full' },
{ path: 'users', component: UserListComponent, title: 'Users' },
{ path: 'audit', component: AuditLogComponent, title: 'Audit log' }
]
}
];// admin/admin-shell.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-admin-shell',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<h2>Admin</h2>
<nav>
<a routerLink="users" routerLinkActive="active">Users</a>
<a routerLink="audit" routerLinkActive="active">Audit log</a>
</nav>
<router-outlet />
`
})
export class AdminShellComponent {}// admin/admin.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class AdminService {
readonly startedAt = new Date();
}// admin/user-list.component.ts
import { Component, inject } from '@angular/core';
import { AdminService } from './admin.service';
@Component({
selector: 'app-user-list',
standalone: true,
template: `<p>Users (admin session since {{ admin.startedAt.toLocaleTimeString() }})</p>`
})
export class UserListComponent {
admin = inject(AdminService);
}// admin/audit-log.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-audit-log',
standalone: true,
template: `<p>Audit log</p>`
})
export class AuditLogComponent {}The admin files import their components statically. That is fine. Those static imports live inside the lazy chunk, so UserListComponent and AuditLogComponent load together with ADMIN_ROUTES.
As with loadComponent, a default export (export default [...] satisfies Routes;) lets you drop the .then(...).
Paths Inside a Lazy Group Are Relative
The parent route already consumed the admin segment. Paths inside ADMIN_ROUTES describe what comes after it: users matches /admin/users. If you write path: 'admin/users' inside the group, the full URL becomes /admin/admin/users.
Route-Level Providers
The providers array on a route creates an environment injector for that route and its descendants. Because the array sits inside the lazy file, AdminService is created only when the admin area first activates, and only components under /admin can inject it. A service declared with providedIn: 'root' and used only by lazy code is also tree-shaken into the lazy chunk. The difference is scope: a root service, once loaded, is one app-wide instance, while a route provider is visible only within its subtree.
What Happens During a Lazy Navigation
The router calls the loader once and caches the result. Later navigations into /admin reuse the cached routes with no network request. The load happens during route matching, before canActivate guards run. The guards chapter covers why that matters: to stop unauthorized users from even downloading a chunk, use canMatch, which runs before the loader.
Verifying That Splitting Actually Happened
Run a production build:
ng buildThe CLI prints two tables, "Initial chunk files" and "Lazy chunk files". Your lazy routes should appear in the second table with names derived from the file, such as admin-routes. If a feature you meant to lazy load is missing from that table, some eager code is importing it.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Feature absent from "Lazy chunk files" | A static `import` of the component or routes file exists somewhere eager, such as a shared barrel `index.ts` or another component's `imports` | Remove the static import; import only through `import()` |
| Error that the loaded value is not a component, or routes are missing | `.then()` omitted on a named export, so the router got the module object | Add `.then(m => m.Name)` or switch to `export default` |
| URLs like `/admin/admin/users` | Child paths repeat the parent segment | Use relative paths inside the group |
| Lazy route never matches; Not Found shows instead | `**` wildcard placed before the lazy route | Keep the wildcard last |
| `NullInjectorError` for a feature service outside the feature | Service registered in route `providers` but injected elsewhere | Move it to `providedIn: 'root'` or keep usage inside the subtree |
| Navigation fails after a deployment | Old clients request chunk file names that no longer exist on the server | Keep old chunks deployed for a while, or catch the `NavigationError` and reload the page |
Choosing What to Lazy Load
Load the landing page and screens most users see in the first seconds eagerly. Lazy loading them only adds a round trip. Lazy load feature areas behind navigation, especially role-specific ones like admin. For a single heavy screen, loadComponent is enough. Once a feature has several related routes or shared services, group it with loadChildren. The cost of lazy loading is a short delay on the first visit to each chunk. The preloading chapter shows how to fetch chunks in the background so that delay disappears.
Exercise
You add { path: 'settings', loadComponent: () => import('./settings/settings.component').then(m => m.SettingsComponent) }, but ng build shows no settings chunk in "Lazy chunk files". The route works. What is the most likely cause, and how do you confirm it?
Show answer
Some eagerly loaded file still imports SettingsComponent statically, for example a barrel file, the root component's imports array, or app.routes.ts itself, so the bundler keeps it in the main bundle. Search the project for static imports of settings.component (and for barrels that re-export it), remove them so the only reference is the dynamic import(), then rebuild and check that a settings chunk appears.
Exercise
A lazy group declared under path 'billing' contains { path: 'billing/invoices', component: InvoicesComponent }. Which URL renders InvoicesComponent, and how should the route be written?
Show answer
It renders at /billing/billing/invoices because paths in a lazy group are relative to the parent that already matched 'billing'. Write it as { path: 'invoices', component: InvoicesComponent } so that it matches /billing/invoices.
Exercise
A service listed in the providers array of the lazy admin route holds a counter. A user visits /admin, increments the counter, goes to /home, then returns to /admin. What value do they see, and why?
Show answer
They see the incremented value. The environment injector created for the route's providers lives on after the user navigates away, so the same AdminService instance is reused when they come back.