Sub topic 2
Lazy Loading a Feature Area with `loadChildren`
Assume you know standalone Angular components, TypeScript imports and exports, and basic Angular Router configuration. A lazy route loads a feature only when navigation needs it. This keeps feature code out of the initial JavaScript bundle.
Lazy loading a feature area with `loadChildren`
loadChildren is a route property that loads a group of child routes. The import() expression is the split point. Angular's build process emits the imported feature as a separate JavaScript chunk.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];The imported file exports a plain Routes array:
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin-dashboard.component';
import { AdminUsersComponent } from './admin-users.component';
export const ADMIN_ROUTES: Routes = [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
];When the user visits /admin, the router fetches the admin chunk and matches its child routes. The application can also lazy load one standalone component with loadComponent, but loadChildren is useful when a feature contains several related pages.
Providing services for a lazy route tree
A route-level providers array creates a route-level environment injector. Services provided there are available to that route and its descendants.
import { Routes } from '@angular/router';
import { AdminService } from './admin.service';
import { AdminDashboardComponent } from './admin-dashboard.component';
export const ADMIN_ROUTES: Routes = [
{
path: '',
providers: [AdminService],
children: [
{ path: '', component: AdminDashboardComponent },
],
},
];This gives the admin route tree its own AdminService instance. Keep feature-only services here when they should not be global.
Preloading lazy routes in the background
Preloading fetches lazy chunks after the initial navigation. PreloadAllModules improves later navigation speed at the cost of background network and download work.
import { ApplicationConfig } from '@angular/core';
import {
PreloadAllModules,
provideRouter,
withPreloading,
} from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withPreloading(PreloadAllModules)),
],
};Use no preloading for the smallest initial network cost. Use selective preloading when only likely routes should download early.
Exercise
What does the import() call in loadChildren control?
Show answer
It creates the lazy-loading split point, allowing the bundler to emit a separate chunk for the feature route group.