Angular Router 15 : Lazy Loading Modules

Yuvaraj S
2 min readDec 25, 2022

--

Hi Guys, In the our previous blogs we learnt almost all route guards of angular ie CanActivate, CanDeactivate, CanActivateChild, and Resolve. Except for CanLoad.

The CanLoad Guard is used to load the modules, hence before going to CanLoad route guard, let’s understand lazy loading modules.

Angular Lazy Loading Module is one of the most important topic in angular. When our application size increases, Our application performance and loading time will decrease. Using angular lazy loading, we can also increase the app performance and loading speed. Let’s see how to implement angular lazy loading.

Firstly I have created 3 components and 3 Modules namely,

  • home.component and home.module
  • contacts.component and contacts.module
  • about.component and about.module

Check for the Live Working Code on Stackblitz
https://stackblitz.com/edit/angular-module-loadlazy

For home module I didn’t use lazy loading module in router. So angular loads everything, as angular is eagerly loading.

As we didn’t implement lazy loading, home module is eagerly loaded. This means angular loads everything that it’s required. So Our bundle size get Increased.
In cases where we need to load the particular module on reaching certain route. Let’s explore reaching ‘’/about’’ route we will load about module and ‘’/contact‘’ will load contacts module. I have created modules according to components.

structure of application

In our about.module.ts

We declare all the routes and components on reaching after ‘’/about‘’ route. When declaring routes we will register our routes with forChild method in RouterModule.

The Same Pattern goes to Contacts module too,
In the routing module file we will import our modules by specifying the path and taking the class name declare it in callback. Like

 {path:'about', loadChildren: ()=> import('./about/about.module').then(x => x.AboutModule) },

Here comes the magic of lazy loading,
In output while navigating to ‘’/about/about-component’’ we will load about module.

— — — — — — — — — End Of Lecture — — — — — — —

Check All lessons of Angular Intermediate Lessons

https://medium.com/@yuvayuvaraj720444/angular-intermediate-lessons-acbea2dfc9b

--

--

Yuvaraj S

Frontend Developer with 6years of experience, I write blogs that are [Easy words + Ground Level Code + Live Working Link]. Angular | React | Javascript | CSS