Lazy loading helps your app load faster by only loading parts when needed. It saves data and improves user experience.
Lazy loading modules with routes in Angular
const routes: Routes = [ { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) } ];
The loadChildren property tells Angular to load the module only when the route is visited.
Use a function that returns a dynamic import() statement for lazy loading.
const routes: Routes = [ { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) } ];
const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) } ];
This example shows an Angular app routing setup where the 'products' module is lazy loaded. The main router loads the ProductsModule only when the user visits '/products'. The ProductsModule has its own route and component.
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) }, { path: '', redirectTo: 'products', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} // products.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { ProductsComponent } from './products.component'; const routes: Routes = [ { path: '', component: ProductsComponent } ]; @NgModule({ declarations: [ProductsComponent], imports: [CommonModule, RouterModule.forChild(routes)] }) export class ProductsModule {} // products.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-products', template: `<h2>Products Page Loaded Lazily!</h2>` }) export class ProductsComponent {}
Lazy loading works best with feature modules, not root modules.
Make sure the lazy loaded module has its own routing configured with RouterModule.forChild().
Use browser DevTools Network tab to see when modules load.
Lazy loading delays loading parts of your app until needed.
Use loadChildren with dynamic import() in routes.
This improves app speed and user experience.