Angular, Lazy Loading, Performance, electro4u.net

07 Jun 2023 Balmiki Mandal 0 Web development

steps on how to implement lazy loading in Angular 11:

  1. Create a new module and a separate routing file.
Code snippet
ng g m lazy-loading --routing
  1. Create a component.
Code snippet
ng g c lazy-loading/lazy-loading-component
  1. Add the link to the header.
Code snippet
<a href="/lazy-loading">Lazy Loading</a>
  1. 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 { }

  1. Set up the route.
Code snippet
const routes: Routes = [
  { path: '', component: AppComponent }
  { path: 'lazy-loading', component: LazyLoadingComponent }
];
  1. 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.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.