A Tour to implement Lazy Loading …

Rashmi Bang
2 min readJun 15, 2021

--

Angular by default loads the components and modules eagerly. That means the entire code is downloaded one time only when the application starts. For smaller websites, it might not matter much that all the modules are loaded at once. But as the app grows, we prefer to have separate modules which are loaded as needed because the size of the application will grow and downloading everything upfront would slow the loading.

Lazy loading is a design-pattern of loading components and modules, as and when they are required.

Implementation

Lets create 2 components, one using the lazy loading module and the other with eager loading module.

ng g c First

After generating the component, we will add the routes in theapp-routing.module.ts file as follows:

const routes: Routes = [
{
path: 'eager', component: FirstComponent
}
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

To make lazy-loading work, we have to group the lazy loading components and directives in a module. So let’s create a feature module first:

ng g module custom --routing

This would create two files, custom.module.ts and custom-routing.module.ts. The first one is the main module file whereas the second one is the routing module file.

Now let’s create a component in this second module:

ng g c --module custom

Provide the name of component (SecondComponent in our case) which has to be loaded lazily, so the custom module routing file will look like this:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {SecondComponent} from "../second/second.component";

const routes: Routes = [
{path: '', component: SecondComponent},
];

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

The custom.module.ts file will look like this (we have not made any changes in this file):

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomRoutingModule } from './custom-routing.module';
import {SecondComponent } from '../Second/Second.component';

@NgModule({
declarations: [
SecondComponent
],
imports: [
CommonModule,
CustomRoutingModule
]
})
export class CustomModule { }

Since we are lazy loading the CustomModule and SecondComponent so the we have to use loadChildren parameter in the path configuration. We can do it like this in app-routing.module.ts:

const routes: Routes = [
{
path: 'eager', component: FirstComponent
},
{
path: 'lazy', loadChildren: () => import('./custom/custom.module').then(module => module.CustomModule)
}
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

Now you can run the application to validate the lazy loading .

--

--