Angular Lazy Loading Modules
Introduction
Lazy loading is a technique in Angular, that helps to load only that module which the user is going to view, rather than loading all the modules together at the start. This technique significantly saves time when the application becomes huge and complex.
For example, when the user navigates to a feature module, lazy loading loads that module only, rather than loading the entire application.
Syntax
The following is the syntax of the loadChildren
property in the Angular router:
const routes: Routes = [
{
path: 'module-name',
loadChildren: 'path/to/module/module-name.module#ModuleNameModule',
},
];
Example
The following example demonstrates how to implement lazy loading in Angular:
- Create a feature module
ng generate module featureModule
- Define routes in your feature module's
RouterModule
:
const featureRoutes: Routes = [
{
path: '',
component: FeatureComponent
}
];
@NgModule({
imports: [RouterModule.forChild(featureRoutes)],
exports: [RouterModule]
})
export class FeatureRoutingModule { }
- Load the feature module:
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
Output
When the user navigates to the /feature
route, Angular loads the FeatureModule
lazily.
Explanation
Lazy loading provides a significant performance boost in large applications, as only that module is loaded which is required.
To implement lazy loading in Angular, you need to create a feature module and define its routes in its RouterModule
.
Then, load the feature module in the main app module's RouterModule
using loadChildren
property along with the path to the feature module.
Use
Angular lazy loading helps improve the application's load time and performance when a large application has multiple feature modules. It loads only that module which is required.
Important Points
- Lazy loading helps to load only that module which is required by the user.
- Angular provides the built-in feature of lazy loading.
- You can create multiple feature modules in a large application.
- Defining routes in features module's
RouterModule
is necessary to load the module lazily.
Summary
Lazy loading is an essential technique for improving performance in large Angular applications. It reduces the initial load time by loading the modules only when required. Using the loadChildren
property in Angular router, you can easily load the modules on demand and improve the performance of your application.