What is lazy loading in Angular and how is it implemented?
Lazy loading in Angular is a technique for loading parts of your application only when they are needed, rather than loading all parts up front. This can greatly improve the performance and startup time of your application, especially for large applications with many components.
In Angular, lazy loading is implemented by splitting your application into multiple smaller chunks, called “modules”, and loading each module only when it’s requested. The main benefit of this approach is that the user only needs to download and parse the code for the components that they need at the moment, reducing the initial load time and overall size of the application.
Here is an example of how to implement lazy loading in Angular:
- Create a separate module for the components that you want to lazy load. This module should contain only the components and dependencies required for that specific feature.
- In your main application module, use the
loadChildren
property of theRouterModule
to load the lazy loaded module when its corresponding route is activated.
Here is an example:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, the lazy
route uses the loadChildren
property to load the LazyModule
when the /lazy
URL is activated. The LazyModule
is loaded asynchronously, so it won’t be loaded until the user navigates to the /lazy
URL. This allows the main application to start up more quickly, as it doesn’t need to download and parse the code for the LazyModule
until it’s needed.