Angular, Lazy Loading, Performance, electro4u.net
steps on how to implement lazy loading in Angular 11:
- Create a new module and a separate routing file.
ng g m lazy-loading --routing
- Create a component.
ng g c lazy-loading/lazy-loading-component
- Add the link to the header.
<a href="/lazy-loading">Lazy Loading</a>
- Implement lazy loading with
loadChildren
.
import { NgModule, Injectable } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LazyLoadingModule } from '@angular/lazy-loading';
@NgModule({ imports: [ RouterModule.forRoot([ { path: '', component: AppComponent } ]), LazyLoadingModule.forChild([ { path: 'lazy-loading', loadChildren: () => import('./lazy-loading/lazy-loading.module').then(m => m.LazyLoadingModule) } ]) ], declarations: [ AppComponent, LazyLoadingComponent ] }) export class AppModule { }
- Set up the route.
const routes: Routes = [
{ path: '', component: AppComponent }
{ path: 'lazy-loading', component: LazyLoadingComponent }
];
- Verify lazy loading.
Open the application in the browser and navigate to the /lazy-loading
route. You should see the Lazy Loading
component without any errors.
Lazy loading is a great way to improve the performance of your Angular application by loading only the modules that are needed. This can be especially helpful for large applications with many modules.