Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 74 ยท Routing

Child Routes and Lazy Loading

Build nested layouts with child routes, split your app into lazy-loaded chunks with loadComponent and loadChildren, and choose a preloading strategy.

A route table with a dozen flat entries is fine for a small site. Real applications have regions: a shell with a header, an admin area with its own sidebar, a course section with tabs. Each region wants its own layout, and each region should only be downloaded when somebody actually visits it. Angular gives you two features for that: child routes (nesting) and lazy loading (code splitting).

Child routes decide what is shown together; lazy loading decides when the code arrives. They combine well, and together they keep the first page fast while the app grows. This lesson builds on Routing Basics and Route Parameters and Navigation.

The real Angular routes and components below are read-only: the site can't run the Angular compiler or a bundler. The runnable examples are stand-ins in plain TypeScript: a nested route matcher that produces a component chain, and a lazy chunk loader with a cache and preloading strategies. The chunk sizes in them are made-up numbers for illustration.

Child routes and nested outlets

A route can have a children array. The parent's component contains its own <router-outlet />, and the matching child renders inside it:

TypeScript
export const routes: Routes = [
  {
    path: 'courses',
    component: CoursesLayoutComponent, // has <router-outlet /> and shared tabs
    children: [
      { path: '', component: CourseListComponent },
      { path: ':id', component: CourseDetailComponent },
      { path: ':id/reviews', component: CourseReviewsComponent },
    ],
  },
  { path: '**', component: NotFoundComponent },
];
HTML
<!-- courses-layout.component.html -->
<h1>Courses</h1>
<nav><a routerLink="/courses">All</a></nav>
<router-outlet />   <!-- the child route renders here -->

The URL /courses/42 matches the parent courses (consuming one segment) and then the child :id (consuming the rest). The parent component stays alive while only the child swaps, so layout state such as an open sidebar survives navigation between children.

flowchart TD
  S["AppComponent<br/>router-outlet"] --> L["CoursesLayoutComponent<br/>router-outlet"]
  L --> D["CourseDetailComponent"]

Outlets nest: each level of the route tree renders into the outlet of the level above.

Two details are worth knowing:

  • Every level needs a matching outlet. A child without an outlet in its parent's template will never show.
  • A route may have children and no component. That's a component-less route, useful to group routes under a shared path prefix, share canActivate guards (see guards) or share providers without adding a wrapper element.

To try the idea, here is a stand-in matcher that walks a route tree and returns the chain of components from the outermost to the innermost. Segments starting with : match anything, just as in the real router:

TypeScript Stand-in: matching a nested route tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each tag is one <router-outlet> level. The settings route has no component of its own, so it adds nothing to the chain, and /courses/42/x fails because no child consumes the trailing segment.

Why lazy loading matters

By default, every component you reference in routes through component: is imported at the top of app.routes.ts, so the bundler puts it all into the initial bundle that every visitor downloads before seeing anything. An admin dashboard, a reporting module and a checkout flow all ship to people who only wanted the home page.

Lazy loading changes the import into a dynamic import(). The bundler (the esbuild-based application builder in a new CLI project) then writes the imported code into a separate file called a chunk, which the browser requests only when the route is first needed.

loadComponent

For a single page, use loadComponent instead of component:

TypeScript
export const routes: Routes = [
  { path: '', component: HomeComponent }, // eager: part of the first bundle
  {
    path: 'pricing',
    loadComponent: () =>
      import('./pricing/pricing.component').then((m) => m.PricingComponent),
  },
];

The function runs the first time the user navigates to /pricing. It returns a promise of the component class; the router waits for it, then renders. If the file has a default export of the component, you can shorten it to loadComponent: () => import('./pricing/pricing.component').

loadChildren

For a whole area of the app, put its routes in their own file and load them as a unit:

TypeScript
// app.routes.ts
export const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
  },
];

// admin/admin.routes.ts
export const ADMIN_ROUTES: Routes = [
  {
    path: '',
    component: AdminLayoutComponent,
    providers: [AdminStore], // a service scoped to this area
    children: [
      { path: 'users', component: UserTableComponent },
      { path: 'reports', component: ReportsComponent },
    ],
  },
];

Everything reachable from admin.routes.ts (the layout, the pages and their imports) lands in the lazy chunk, unless another part of the app also imports it statically. Routes loaded this way can declare providers, which create an environment injector for that area, a topic for providers and scopes.

flowchart LR
  subgraph first["Initial bundle (everyone)"]
    A["Shell, Home"]
  end
  subgraph lazy["Lazy chunks (on demand)"]
    B["admin"]
    C["reports"]
  end
  A -. "visit /admin" .-> B
  A -. "visit /reports" .-> C

Only the shell and home page are downloaded up front; each area's chunk is fetched on its first visit.

Watching out for accidental static imports

Splitting only works if nothing else imports the code statically. If AdminLayoutComponent is also imported from app.component.ts, the bundler has to keep it in the main bundle, and the lazy route gains nothing. After a production ng build, the CLI prints a table of "Initial chunk files" and "Lazy chunk files" with their sizes; check that your feature areas appear in the lazy list.

Preloading strategies

Lazy loading has one cost: the first visit to a lazy route waits for a download. Preloading fetches lazy chunks in the background after the app has started, so later navigation feels instant. You choose a strategy with withPreloading:

TypeScript
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';

provideRouter(routes, withPreloading(PreloadAllModules));
  • The default is no preloading: chunks load only on navigation.
  • PreloadAllModules fetches every lazy route after the initial load. Simple and often fine for small apps, wasteful for large ones on slow connections.
  • A custom strategy implements PreloadingStrategy and decides per route. A common one preloads only routes flagged with data: { preload: true }:
TypeScript
@Injectable({ providedIn: 'root' })
export class SelectivePreloading implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
    return route.data?.['preload'] ? load() : of(null);
  }
}

// provideRouter(routes, withPreloading(SelectivePreloading));
// { path: 'admin', loadChildren: ..., data: { preload: true } }

Pair preloading with the canMatch guard from the next lesson if some areas shouldn't be fetched at all for users who lack access.

A runnable lazy loader

The stand-in below mimics what the router does with loadComponent: it calls a loader on the first visit, caches the result so later visits are free, and optionally preloads in the background. The log records each simulated download. The sizes are invented for the demo.

TypeScript Stand-in: a lazy loader with a cache and preloading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Compare the three runs. With no preloading every first visit triggers a download, with flagged only pricing is fetched ahead of time, and with all everything is downloaded before the user clicks, including reports, which nobody visited. The second visit to admin is always served from the cache, just as the router keeps a loaded route's code once it has arrived.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is required for a child route's component to appear on screen?

    Child routes render into the outlet of their parent's component. Without an outlet in the parent template, nothing shows.
  2. 2. What does loadComponent do compared with component?

    A dynamic import lets the bundler split the code into a lazy chunk, so visitors who never go to the route never download it.
  3. 3. Your admin route uses loadChildren, but the admin bundle is still in main.js. What is the most likely reason?

    A static import anywhere in the eager graph pulls the code into the initial bundle, defeating the split. Check the CLI's list of lazy chunks after a production build.
  4. 4. Which preloading choice downloads every lazy route after startup?

    PreloadAllModules loads all lazy routes in the background after the app starts. A custom strategy lets you pick routes instead.

Summary

  • children nest routes; the parent component hosts a <router-outlet /> where the matching child renders, and a parent without a component just groups routes.
  • Lazy loading uses dynamic import() through loadComponent (one page) or loadChildren (a whole route file) so the bundler emits separate chunks.
  • Static imports of the same code elsewhere defeat code splitting; check the build's "Lazy chunk files" list.
  • Route-level providers create a scoped injector for a feature area.
  • Preloading (withPreloading) fetches chunks in the background: none by default, PreloadAllModules for everything, or a custom PreloadingStrategy for selected routes.
  • In this lesson the Angular code is read-only; the matcher and lazy loader are stand-ins with invented sizes.

Next: Guards, Resolvers and Router Events