What is lazy loading in Angular explain with an example?
Lazy loading is a design pattern used in Angular to load parts of a web application only when they are needed. It’s a technique for optimizing the loading speed of a web application by dividing the application into smaller chunks and loading each chunk only when it’s required.
Here is an example to demonstrate lazy loading in Angular:
Suppose you have a large web application that contains several modules, such as a dashboard module, a user management module, and a settings module. Instead of loading all of these modules at once when the application starts, you can use lazy loading to load each module only when the user navigates to that particular section of the application.
Here’s how you can implement lazy loading in Angular:
- Create separate modules for each section of the application, such as a DashboardModule, a UserModule, and a SettingsModule.
- In the routing configuration, use the
loadChildren
property to specify the module to be loaded lazily. Here’s an example:
const routes: Routes = [
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) },
{ path: 'users', loadChildren: () => import('./users/users.module').then(m => m.UserModule) },
{ path: 'settings', loadChildren: () => import('./settings/settings.module').then(m => m.SettingsModule) },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
In this example, each module is loaded only when the corresponding URL is visited by the user. This results in faster initial load times and improved overall performance of the application.