Sub topic 4
Lazy loading a single component with loadComponent
This chapter assumes you can write standalone components, define routes with the Angular Router, and run ng build. It also assumes you know that import() returns a Promise. The chapter covers loadComponent: what it does, how the router uses it, how to verify the result, and the errors people commonly hit.
What loadComponent does
A route normally names its component with the component property. That requires a static import at the top of the routes file, so the bundler places the component in the main bundle. The component downloads even if the user never visits the route.
loadComponent replaces component. It is a function that returns a Promise (or Observable) of a component class. The router calls it the first time the route matches, waits for the result, and then renders the component.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: '',
loadComponent: () =>
import('./home/home.component').then(m => m.HomeComponent),
},
];Three things happen here:
- The arrow function does not run when the route table is defined. It runs only when the router matches
''for the first time. import('./home/home.component')is a dynamic import. The bundler sees the string literal and emits a separate chunk (a separate JavaScript file) for that module and the code only it needs..then(m => m.HomeComponent)picks the component class out of the loaded module and returns it to the router.
Why the static import must go
The split only works if nothing else in the main bundle imports the component statically. The bundler decides chunk boundaries from the import graph. If one file reaches the module through a normal import statement, the module stays in the main bundle, and the dynamic import() no longer creates a separate chunk.
This is the most common reason a lazy route "works" but saves nothing. The following version looks lazy but is not:
import { Routes } from '@angular/router';
// Static import: HomeComponent is now part of the main bundle.
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{
path: '',
loadComponent: () =>
import('./home/home.component').then(m => m.HomeComponent),
},
];In this file the static import is unused, so the TypeScript compiler may drop it. In a real application the static import usually sits in another file, such as a shared barrel (index.ts) or another component's imports array. The effect is the same.
Converting an eager route to a lazy one
Suppose you start with this eager route:
import { Routes } from '@angular/router';
import { ReportsComponent } from './reports/reports.component';
export const routes: Routes = [
{ path: 'reports', component: ReportsComponent },
];The conversion has two steps.
- Delete the static
importofReportsComponentfrom the routes file. - Replace
component: ReportsComponentwith aloadComponentfunction.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'reports',
loadComponent: () =>
import('./reports/reports.component').then(m => m.ReportsComponent),
},
];Then search the project for other references to ReportsComponent. If another standalone component lists it in imports, or a template uses <app-reports>, the class is still in the main bundle through that path.
Requirements on the component
loadComponent works with standalone components. The component declares its own dependencies in its imports array, so the router can render it without an NgModule.
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-reports',
standalone: true,
imports: [DatePipe],
template: `<h1>Reports</h1><p>{{ today | date }}</p>`,
})
export class ReportsComponent {
today = new Date();
}In recent Angular versions standalone: true is the default, so you can omit it. Keep it if your project targets an older version.
Default exports
The router also accepts a module whose default export is the component. This lets you drop the .then(...) step:
import { Component } from '@angular/core';
@Component({
selector: 'app-settings',
template: `<h1>Settings</h1>`,
})
export default class SettingsComponent {}import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'settings',
loadComponent: () => import('./settings/settings.component'),
},
];The trade-off is that default exports make renames and automatic imports less reliable, and some teams ban them in style guides. Use whichever convention your codebase already follows.
What the user sees while the chunk loads
On a fast connection the chunk arrives in milliseconds. On a slow one, the router does not finish the navigation until the Promise resolves. The old view stays on screen and the URL does not change yet. Nothing tells the user that work is in progress unless you add something.
The router emits events you can use. NavigationStart fires when navigation begins, and NavigationEnd, NavigationCancel or NavigationError fires when it finishes. This service-free example shows a loading flag in the root component:
import { Component, inject, signal } from '@angular/core';
import {
Router,
RouterOutlet,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError,
} from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
template: `
@if (loading()) {
<p>Loading...</p>
}
<router-outlet />
`,
})
export class AppComponent {
loading = signal(false);
constructor() {
inject(Router).events.subscribe(event => {
if (event instanceof NavigationStart) {
this.loading.set(true);
} else if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
this.loading.set(false);
}
});
}
}Because the loading flag covers the whole navigation, it also shows during guards and resolvers, not only during the chunk download. For most applications that is the behavior you want.
When the chunk fails to load
A chunk download is a network request, so it can fail. Typical causes are a dropped connection or a new deployment that deleted the old chunk files while a user still had the old index.html open. The Promise rejects, the router emits NavigationError, and the navigation does not complete.
You can handle this in two places. The first is the loadComponent function itself:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'reports',
loadComponent: () =>
import('./reports/reports.component')
.then(m => m.ReportsComponent)
.catch(err => {
console.error('Could not load reports chunk', err);
throw err;
}),
},
];Rethrowing keeps the router informed. If you swallow the error and return nothing, the router receives undefined instead of a component class and fails with a less helpful message.
The second place is a global handler using withNavigationErrorHandler:
import { ApplicationConfig, inject } from '@angular/core';
import { provideRouter, withNavigationErrorHandler, Router } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withNavigationErrorHandler(error => {
// Typical response to a stale deployment: reload to get fresh files.
console.error('Navigation failed', error);
inject(Router).navigateByUrl('/error');
}),
),
],
};A full page reload is a common recovery for stale deployments, because it fetches the new index.html that points at the new chunk names. Whether to reload automatically or show a message is a product decision.
Verifying the split
Do not assume the split worked. Run a production build and read the output.
ng buildThe CLI prints a table of initial chunks and a table of lazy chunks. A successful split shows the component in the lazy table:
| Section | Example entry | Meaning |
|---|---|---|
| Initial chunk files | `main-ABC123.js` | Downloaded on first page load |
| Initial chunk files | `polyfills-DEF456.js` | Downloaded on first page load |
| Lazy chunk files | `reports-component-GHI789.js` | Downloaded when the route first activates |
File names and hashes differ between versions. What matters is that a chunk named after your component appears under the lazy section. If it does not, a static import is still pulling the component into the main bundle.
You can also check in the browser. Open the Network panel, filter by JS, load the home page, and confirm the reports chunk is absent. Navigate to /reports and confirm it appears at that moment. A second visit to the route does not request it again, because the router and the browser module system cache the result.
Common mistakes
- A static import elsewhere. A barrel file, a shared component's
importsarray, or a service that references the class keeps it in the main bundle. - A wrong export name.
.then(m => m.ReportComponent)returnsundefinedif the class isReportsComponent. TypeScript usually catches this, but adefaultexport mismatch does not always fail at compile time. - Using
componentandloadComponenttogether. A route takes one or the other. Pick one. - Building a non-literal path.
import(somePath + '.ts')cannot be analyzed by the bundler. Always pass a string literal. - Lazy loading the landing page. If the first route the user sees is lazy, the browser must download the main bundle and then the chunk in sequence. Keep the first screen eager, or preload it, when load time is the priority.
- Forgetting the loading state. The app seems frozen on slow networks. Add a visible indicator.
Exercises
Exercise
A route is written with loadComponent: () => import('./billing/billing.component').then(m => m.BillingComponent). After ng build, no billing chunk appears in the lazy chunk list. What is the most likely cause, and where would you look for it?
Show answer
Something in the main bundle's import graph imports BillingComponent statically, so the bundler keeps it in the main bundle. Search the project for billing.component and BillingComponent. Check the routes file, barrel index.ts files, and the imports arrays of other standalone components. Remove the static reference and rebuild.
Exercise
Rewrite this eager route so the component loads lazily, and name the second change you must make outside the route object.
{ path: 'profile', component: ProfileComponent }
Show answer
{ path: 'profile', loadComponent: () => import('./profile/profile.component').then(m => m.ProfileComponent) }. The second change is to delete the static import { ProfileComponent } from ... line at the top of the routes file, and to check that no other file references the class.
Exercise
A user clicks a link to a lazy route on a flaky connection and the chunk request fails. What does the router emit, and how does the user's view behave in the meantime?
Show answer
The Promise returned by loadComponent rejects and the router emits NavigationError. Until then the old view stays on screen and the URL does not change, because the navigation has not completed. You can handle the failure with a catch in the loadComponent function (rethrowing the error) or with withNavigationErrorHandler in provideRouter.