Sub topic 5
Lazy-loading features with the router
This chapter assumes you know TypeScript, standalone components, and the basics of the Angular Router (Routes, provideRouter, RouterOutlet). It builds on the feature folders from the previous chapters. Here you connect those folders to the router so each feature becomes a separate piece of JavaScript that the browser downloads only when it is needed.
Why lazy loading fits feature folders
A feature folder has one entry point: its route file. That makes the route file the natural place to cut the bundle. The application's main bundle then contains only the shell, the root routes, and the code in core. Each feature is built into its own chunk, which is a separate JavaScript file the browser fetches on demand.
The browser-facing benefit is a smaller initial download. The structural benefit matters more in a large codebase. A feature that is lazy-loaded cannot be referenced by static imports from the rest of the app. If it were, the bundler would pull it into the main bundle and the laziness would disappear. Lazy loading therefore enforces the feature boundary at build time.
The app-level routes file
The root routes file does one job: it maps a URL prefix to a feature.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
{
path: 'customers',
loadChildren: () =>
import('./customers/customers.routes').then((m) => m.CUSTOMERS_ROUTES),
},
];loadChildren takes a function that returns a promise of a Routes array. The expression import('./orders/orders.routes') is a dynamic import. The bundler sees it and emits a separate chunk for orders.routes.ts and everything only it imports. The router calls the function the first time a URL starting with orders is navigated to, and it caches the result. Later navigations reuse the loaded routes.
If the route file has a default export, you can drop the .then:
// orders.routes.ts
export default [
{ path: '', loadComponent: () => import('./feature/order-list.component').then((m) => m.OrderListComponent) },
] satisfies Routes;// app.routes.ts
{ path: 'orders', loadChildren: () => import('./orders/orders.routes') }The named export is easier to search for and to refactor, so many teams prefer it. Pick one style and keep it across all features.
The feature's route file
Inside a feature, loadComponent does for a single component what loadChildren does for a set of routes. It lazy-loads a standalone component.
import { Routes } from '@angular/router';
import { OrdersStore } from './data-access/orders.store';
export const ORDERS_ROUTES: Routes = [
{
path: '',
providers: [OrdersStore],
children: [
{
path: '',
loadComponent: () =>
import('./feature/order-list.component').then((m) => m.OrderListComponent),
},
{
path: ':id',
loadComponent: () =>
import('./feature/order-detail.component').then((m) => m.OrderDetailComponent),
},
],
},
];There are two levels of splitting here. The orders chunk holds this route file and the store. Each page component is a further chunk, loaded when its route is first activated. Whether the second level is worth it depends on page size. A tiny detail page that is almost always visited after the list gains little from its own chunk. A heavy page, such as one that imports a charting library, gains a lot.
The empty-path parent route with providers and children is a layout-less grouping route. It renders no component of its own. Its only job is to hold the providers, so the store is shared by both child pages. The next chapter covers that in detail.
What happens during navigation
The following diagram shows the first visit to /orders.
The two requests are sequential. The router cannot know which child route matches until the first chunk has arrived. On a slow connection this waterfall is visible, and preloading (below) is the usual fix.
Preloading
By default, a lazy chunk is fetched only when the user navigates to it. A preloading strategy tells the router to fetch lazy routes in the background after the initial navigation completes. You configure it in the application config.
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withPreloading(PreloadAllModules)),
provideHttpClient(),
],
};PreloadAllModules downloads every loadChildren chunk once the app is idle. This keeps the small initial bundle and removes most of the click-time delay. The cost is bandwidth. On a metered connection, or in an app with dozens of rarely used features, you download code the user may never run.
| Strategy | Behavior | Use when |
|---|---|---|
| `NoPreloading` (default) | Load on first navigation only | Features are large or rarely visited |
| `PreloadAllModules` | Load all lazy routes after startup | Few features, good network assumptions |
| Custom `PreloadingStrategy` | Load routes you flag, such as `data: { preload: true }` | A few hot features should be ready, the rest should not |
A custom strategy is a class implementing PreloadingStrategy with a preload(route, load) method. It returns load() for routes you want and of(null) for the rest. Note that preloading applies to loadChildren. It does not preload loadComponent routes unless you use a strategy that handles them.
Guarding a lazy feature
A guard can stop a user from entering a feature. The choice of guard type decides whether the chunk is downloaded first.
canActivateruns after the route has matched. For aloadChildrenroute, the router has already started loading the feature.canMatchruns while the router is matching. If it returnsfalse, the route is skipped as if it did not exist, and the chunk is never downloaded.
For a feature that a user is not allowed to see, canMatch is usually correct. The code is not sent to people who cannot use it.
import { Injectable, inject } from '@angular/core';
import { CanMatchFn, Router, Routes } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthService {
isLoggedIn(): boolean {
return localStorage.getItem('token') !== null;
}
}
export const authenticatedGuard: CanMatchFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.createUrlTree(['/login']);
};
export const routes: Routes = [
{
path: 'orders',
canMatch: [authenticatedGuard],
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
];Returning a UrlTree redirects. Returning false from canMatch makes the router try the next route that matches the same URL, which ends at your wildcard route if you have one.
Common errors
A static import defeats lazy loading. If any eagerly loaded file imports from a lazy feature with a plain import { X } from './orders/...', the bundler includes that code in the main chunk. The usual cause is another feature importing a component or service from the orders folder. The build often prints a warning that a module is both statically and dynamically imported. Treat that warning as a boundary violation. Import through the feature's barrel only for types and for the route file, and use import type for types, which is erased at compile time.
Barrels can pull in more than you meant. A barrel that re-exports components, the store, and the routes makes any importer depend on all of them. If your app-level routes import ORDERS_ROUTES from the barrel statically, the whole feature lands in the main bundle. Keep the dynamic import() pointing at the route file or the barrel, never a static import in the root routes.
Providers in the root injector. A service marked providedIn: 'root' is available everywhere, but if it lives in a lazy feature and the root code injects it, the build must include it eagerly. Keep feature stores unprovided (@Injectable()) and list them in the route's providers.
Route order and wildcards. The router uses the first match. Put specific paths before parameterized ones, and put the ** wildcard last in the root array. A wildcard placed before a lazy route hides the feature.
Relative links inside a lazy feature. Links such as routerLink="./42" resolve against the current route, so they keep working if you later mount the feature under a different prefix. Hard-coded absolute links like /orders/42 break when the prefix changes.
Verify, do not assume. Run a production build and read the list of emitted chunks. Each lazy feature should appear as its own file. You can also open the browser's network tab, load the home page, and confirm that no orders chunk is requested until you navigate there (or until preloading fetches it).
Summary of decisions
- Map each URL prefix to one feature with
loadChildrenin the root routes. - Use
loadComponentfor pages inside a feature when a page is heavy enough to justify its own chunk. - Choose a preloading strategy deliberately. The default does none.
- Use
canMatchto avoid downloading features a user cannot enter. - Never import lazy feature code statically from eager code.
Exercise
Your root routes use loadChildren for orders, yet a production build shows the orders code inside main.js. The customers feature has import { OrderSummaryComponent } from '../orders/feature/order-summary.component'; at the top of one of its files, and customers is loaded eagerly by a shell component. What is the cause, and how would you fix it?
Show answer
The static import from eagerly loaded code makes the bundler include the orders component, and everything it imports, in the main bundle. A dynamic import() elsewhere does not change that. Fix it by removing the static import. If the shared piece is a UI component, move it to a shared or ui library that both features import. If the customers feature only needs to show order data, use the orders feature's public API (types only, with import type) or communicate through a shared data-access layer. Then rebuild and confirm a separate orders chunk appears.
Exercise
You want users who are not logged in never to download the orders chunk. Which route property do you use, canActivate or canMatch, and why?
Show answer
Use canMatch. It runs during route matching, before the router calls loadChildren, so a false result means the chunk is never requested. canActivate runs after the route has matched, by which point loading of the lazy routes has already begun.