• Angular
  • React
  • NextJs
  • Sass

How to Implement Lazy Loading in Angular

By Webrecto, August 27, 2023

In this article, We will learn how to reduce large application load time with the help of RoutingModule.
Lazy loading is a design pattern that is used to load feature modules, components, and other files as per user demand. Lazy loading helps to reduce module loading time in the application and it helps to keep the bundle size small. In application lazy loading does not load everything at once, the modules are loaded asynchronously. It only loads what the user wants to navigate first to routes.

The lazy loading technique is not used in small applications. It is used in large applications to reduce loading time. In angular applications by default NgModules are eagerly loaded. Due to this all NgModules try to load as soon as possible. We use lazy loading to stop all NgModules loading at the same time.

Routes Configuration:

AppRoutingModule

const routes: Routes = [
  {
    path: '', // path name
    loadChildren: () => import('./employee/employee.module').then(mod => mod.EmployeeModule) // Module name
  }
];

In the above syntax, We configure Routes in AppRoutingModule, Angular provides the loadChildren property to navigate the feature module. It specifies the module that needs to be lazy loaded.

Project Structure

How to Implement Lazy loading in Angular

Lazy Loading Example:

In this below example, we will set up a demo project and use lazy loading for component navigation. Here we will create two feature modules one is the customer and the other is the employee module.

Step 1:

I have created two feature modules inside the root app folder. In this folder I have added two routing module files, one is the employee.routing.module and the other is the customer.routing.module.

In the example given below, we will import RouterModule and Routes from the '@angular/router' routing module, and one EmployeeComponent import from the employee folder. As per the requirement, we can add here more than one component related to the employee feature module in the employee-routing.module.

src/app/employee/employee.routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmployeeComponent }  from './employee.component';

const employeeRoutes: Routes = [
	{ 
	  path: '',
          component: EmployeeComponent
	}	
];

@NgModule({
  imports: [ RouterModule.forChild(employeeRoutes) ],
  exports: [ RouterModule ]
})
export class EmployeeRoutingModule { } 

In the below customer.routing.module we have added the same component related to the customer feature module.

src/app/customer/customer.routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CustomerComponent }  from './customer.component';

const customerRoutes: Routes = [
	{ 
	  path: '',
          component: CustomerComponent
	}	
];

@NgModule({
  imports: [ RouterModule.forChild(customerRoutes) ],
  exports: [ RouterModule ]
})
export class CustomerRoutingModule { } 

In the above example, we are using a blank path for redirecting components from the customer.routing.module. In the application when loadChildren navigates the feature module, It redirects the employee or customer component.

Step 2:

In the next step, I create the employee.module and customer.module in both feature modules and also import RoutingModule and component. In the feature modules, we import @NgModule from '@angular/core', and we declare RoutingModule in the imports[] array and component names in the declarations[] array.

src/app/employee/employee.module.ts

import { NgModule }   from '@angular/core';
import { EmployeeComponent }  from './employee.component';
import { EmployeeRoutingModule }  from './employee.routing.module';

@NgModule({
  imports: [     
    EmployeeRoutingModule
  ], 
  declarations: [
    EmployeeComponent
  ],
  providers: [ ]
})
export class EmployeeModule {
  constructor() {
    console.log('EmployeeModule loaded.');
  }
} 

src/app/customer/customer.module.ts

import { NgModule }   from '@angular/core';
import { CustomerComponent }  from './customer.component';
import { CustomerRoutingModule }  from './customer.routing.module';

@NgModule({
  imports: [     
    CustomerRoutingModule
  ], 
  declarations: [
    CustomerComponent
  ],
  providers: [ ]
})
export class CustomerModule {
  constructor() {
    console.log('CustomerModule loaded.');
  }
} 

Step 3:

I have created app.routing.module in the app folder to configure all routing paths. In the app.routing.module, we use the loadChildren property to load employee and customer feature modules in the application routing module.

src/app/app.routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
   {
      path: 'customer',
      loadChildren: () => import('./customer/customer.module').then(mod => mod.CustomerModule)
   },
   {
      path: 'employee',
      loadChildren: () => import('./employee/employee.module').then(mod => mod.EmployeeModule)
   },
   {
      path: '',
      redirectTo: '',
      pathMatch: 'full'
   }
];
@NgModule({
   imports: [
      RouterModule.forRoot(routes)
   ],
   exports: [
      RouterModule
   ]
})
export class AppRoutingModule { } 

Step 4:

In the below example, we import only the AppRoutingModule and app components and do not add any lazy load feature module in app.module.

src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app.routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 5:

We use the RouterLink directive for navigation to route across the application.

src/app/app.component.html

<div>
  <h2>Lazy Loading Example:: WebRecto</h2>
  <button routerLink="/" routerLinkActive="active">Home</button>  
  <button routerLink="/employee" routerLinkActive="active">Employee</button>  
  <button routerLink="/customer" routerLinkActive="active">Customer</button>    
</div>
<div>
    <router-outlet></router-outlet>
</div>

Output:

How to Implement Lazy loading in Angular

Reference

Download Source Code