Angular Routing & Modules
Lazy loading in Angular lets you load feature modules only when their routes are visited, instead of loading everything at application startup. This reduces the initial bundle size and makes your app feel faster, especially for large projects with many features.
RouterModule.forChild() – Used inside feature modules for their own routing configuration.loadChildren – A route property in the root routing module that points to the lazily loaded module.To use lazy loading, you typically:
ProductsModule).RouterModule.forChild().loadChildren property that points to this module.The lazy-loaded module is only requested when the user hits a specific route such as /products, which keeps the initial load light and improves perceived performance.
products.module.ts
// Feature module with its own routing
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductsComponent } from './products.component';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: ProductsComponent }
];
@NgModule({
declarations: [ProductsComponent],
imports: [CommonModule, RouterModule.forChild(routes)]
})
export class ProductsModule { }
app-routing.module.ts
// Root routing configuration with lazy loading
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)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
ProductsModule defines a route with an empty path ('') that maps to ProductsComponent. When the module is loaded, visiting /products shows this component.loadChildren property uses a dynamic import to reference ./products/products.module and resolve ProductsModule./products, Angular automatically:
ProductsModule.ProductsComponent in the configured router outlet./products, the module code is not loaded, which reduces the initial bundle size and speeds up app startup.RouterModule.forChild() inside lazy-loaded feature modules; use forRoot() only in the main app routing module.CanLoad or CanActivate) to protect secure sections.loadChildren to avoid runtime loading errors.UsersModule in your Angular app and configure it for lazy loading on the route /users.UserListComponent, UserDetailComponent) and set up child routes using RouterModule.forChild().UsersModule with a CanLoad guard so that only authenticated users can load it.