Lazy loading in Angular is a technique that allows you to load modules and their associated resources (components, services, etc.) on-demand, rather than loading everything upfront when the application starts. This helps to improve the initial loading time of the application and optimize the overall performance.
By default, Angular loads all modules and their associated resources when the application is launched. However, with lazy loading, you can split your application into feature modules and load them dynamically only when they are needed. This way, you can reduce the initial bundle size and load only the necessary code for the current route or feature.
To implement lazy loading in Angular, you need to follow these steps:
1. Create Feature Modules: Divide your application into feature modules that encapsulate related components, services, and other resources. Each feature module will have its own routing configuration.
2. Configure Routes: In the main routing configuration of your application, set up the routes for the feature modules using the `loadChildren` property instead of `component`. The `loadChildren` property specifies the path to the module file to be loaded lazily.
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) },
// other routes...
];
3. Create Feature Module: In each feature module, define its own routing configuration using the `RouterModule.forChild()` method.
const routes: Routes = [
{ path: '', component: ProductListComponent },
{ path: 'details/:id', component: ProductDetailsComponent },
// other routes specific to the feature module...
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ProductsRoutingModule { }
4. Build and Serve: Build your Angular application using the Angular CLI. When you navigate to a route associated with a lazy-loaded module, Angular will fetch and load the necessary module and its resources on-demand.
Lazy loading allows you to optimize your application's performance by splitting it into smaller modules that can be loaded when needed. It helps reduce the initial loading time and improves the user experience, especially for larger applications with multiple features.
For more details, checkout this angular's official link to understand lazy loading -
Lazy loading in Angular