How To Use Lazy Loading In An Angular Project

In this article, we will learn how to use lazy loading in an angular project

Create Angular Project

Now let’s create an Angular Project by using the following command,

ng new lazy-loading-demo

Create a module and separate routing file named lazy-loading. The purpose of independent routing is to handle all the components associated with angular lazy-loading module

ng g m lazy-loading –routing

Create a component named lazy-demo within the lazy-loading module,

ng g c lazy-demo

Adding a link in the header on whose route we will implement lazy loading.


<li class="nav-item">  
   <a class="nav-link" [routerLink]="['/lazy-loading']">  
      Lazy Loading  

Lazy load the component, which will be displayed on the route – /lazy-loading Make necessary changes in app-routing.module.ts. Here we will load the module lazily using loadChildren


   path: 'lazy-loading',  
   loadChildren: () => import('./lazy-loading/lazy-loading.module')  
   .then(m => m.LazyLoadingModule)  

Set up the route in lazy-loading-routing.module.ts.

import { NgModule } from '@angular/core';  
import { RouterModule, Routes } from '@angular/router';  
import { LazyDemoComponent } from './lazy-demo/lazy-demo.component';  
const routes: Routes = [  
 { path: '', component: LazyDemoComponent }  
    imports: [RouterModule.forChild(routes)],  
    exports: [RouterModule]  
export class LazyLoadingRoutingModule { }

If the above import option gives error, try like this,

import { LazyDemoComponent } from"E:/Pranam/Git Repository Projects/Angular-Lazy-Loading-Example/src/app/lazy-demo/lazy-demo.component";

Now run application.

Go to the terminal and execute the “ng serve” command.

Now go to the browser https://localhost:4200



You will observe that main.js is being served on refreshing the browser. And the Lazy Loading module is loaded only on hitting the route /lazy-loading.



Hope you understand the article , If you still have any questions or queries then please let me know in the comment section, I’ll respond to you as soon as possible.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories