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
// 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)
}
];
// 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:
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 ?