How to Lazy Load Nested Routes ?

For nested routes, we can use the loadChildren property instead of loadComponent, so that they are loaded only when required.

Using below commands we can create sign-in and sign-up components, and add an auth.router.ts to handle routing for auth components.

ng g c auth/sign-in
ng g c auth/sign-up
JavaScript
// app.router.ts

import { Routes } from '@angular/router';

export const routes: Routes = [
    {
        path: '',
        redirectTo: 'auth',
        pathMatch: 'full',
    },
    {
        path: 'auth',
        loadChildren: () => import('./auth/auth.router')
            .then(m => m.AuthRoutes)
    }
];
JavaScript
// auth.router.ts

import { Routes } from '@angular/router';

export const AuthRoutes: Routes = [
    {
        path: '',
        redirectTo: 'sign-in',
        pathMatch: 'full',
    },
    {
        path: 'sign-in',
        loadComponent: () =>
            import('./sign-in/sign-in.component')
                .then((c) => c.SignInComponent)
    },
    {
        path: 'sign-up',
        loadComponent: () =>
            import('./sign-up/sign-up.component')
                .then((c) => c.SignUpComponent)
    }
];

Output:

Lazy loading Angular nested routes

Angular application build output

Here when we visit auth/sign-in we observe that two chunks are loaded, that is because we had lazy loaded our nested routes and also the sign-in route. Also in the build output we have different chunks for each of our lazy loaded asset.



Implementing Lazy Loading in Angular

Angular applications often consist of various modules and components, which can result in longer initial load times, especially for larger applications. To address this issue and improve performance, Angular provides lazy loading—a technique that defers the loading of certain modules until they are needed.

In this article, we’ll learn more about lazy loading in Angular and how we can implement it in our project.

Table of Content

  • What is Lazy Loading?
  • Why Use Lazy Loading ?
  • How to Lazy Load Routes ?
  • How to Lazy Load Nested Routes ?

Similar Reads

What is Lazy Loading?

Lazy loading is a strategy used to optimize the loading time of an Angular application by loading modules only when they are required. Instead of loading all modules and their associated components at once during the initial application load, lazy loading allows modules to be loaded asynchronously as the user navigates to the corresponding routes. This results in faster initial load times and improved overall performance, especially for larger applications with complex routing structures....

Why Use Lazy Loading ?

It offers several benefits, which includes:...

How to Lazy Load Routes ?

Step 1: Create a new Angular application using the following command....

How to Lazy Load Nested Routes ?

For nested routes, we can use the loadChildren property instead of loadComponent, so that they are loaded only when required....