DEV Community

Cover image for Lazy loading in Angular with example
Dhanush
Dhanush

Posted on • Edited on • Originally published at c-sharpcorner.com

Lazy loading in Angular with example

Introduction:

In this article we will see about lazy loading concept in Angular with an example for your understanding.

Lazy loading:

Instead of loading all the modules and components in an application it allows only selected module and components to load thus reducing the loading time. Lazy loading feature loads components, modules, and other files of Angular application only when required. This concept is used in complex and larger applications. Lazy loading concept makes an application very fast and uses less memory.

Let us see one example on this lazy loading,

Eg:

We will start by creating a new Angular application for easy understanding,

Step-1 : Open a command prompt or terminal. Create a new project,

> ng new LazyDemo
Enter fullscreen mode Exit fullscreen mode

create new application
make sure to allow routing when creating new project or you can simply use the command : > ng new LazyDemo — routing

> cd LazyDemo
Enter fullscreen mode Exit fullscreen mode

Step-2 : Create 3 components or any numbers of your choice just for demo purpose I’m creating 3 components,

> ng generate component Number1
  ng generate component Number2
  ng generate component Number3
Enter fullscreen mode Exit fullscreen mode

create 3 components

Step-3 : Create respective module files in each of the component folders,

> Number1.module.ts
  Number2.module.ts
  Number3.module.ts
Enter fullscreen mode Exit fullscreen mode

Now our file/folder structure will look like this,
Folder structure
Step-4 : Create a respective router module file in each component folder,

> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts
Enter fullscreen mode Exit fullscreen mode

Number1-routing.module.ts
Step-5 : Import the Router Module in the main application module app.module.ts,

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],
Enter fullscreen mode Exit fullscreen mode

Since we have enabled routing at beginning it will be already imported in app.module.ts, In case you forget to apply routing at beginning you can add this, otherwise you can skip this step.

Step-6 : Add the code in their own routing modules, Add following code in Number1-routing.module.ts,

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number1Component } from "./number1.component";
const routes: Routes = [
    { path:"", component: Number1Component }
];
@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})
export class Number1RouterModule{}
Enter fullscreen mode Exit fullscreen mode

Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.
Image description
Similarly add the codes in Number2-routing.module.ts and Number3-routing.module.ts.

In Number2-routing.module.ts add the following codes,

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number2Component } from "./number2.component";
const routes: Routes = [
    { path:"", component: Number2Component }
];
@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})
export class Number2RouterModule{}
Enter fullscreen mode Exit fullscreen mode

In Number3-routing.module.ts add the following codes,

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number3Component } from "./number3.component";
const routes: Routes = [
    { path:"", component: Number3Component }
];
@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})
export class Number3RouterModule{}
Enter fullscreen mode Exit fullscreen mode

In Number1.module.ts add following code,

import { NgModule } from "@angular/core";
import { Number1RouterModule } from "./Number1-routing.module";
import { Number1Component } from "./number1.component";
@NgModule({
    declarations:[Number1Component],
    imports:[Number1RouterModule],
    providers: []
})
export class Number1Module{
}
Enter fullscreen mode Exit fullscreen mode

number1.module.ts
Similarly add same in the other two files Number2.module.ts and Number3.module.ts,

In Number2.module.ts add the following code,

import { NgModule } from "@angular/core";
import { Number2RouterModule } from "./Number2-routing.module";
import { Number2Component } from "./number2.component";
@NgModule({
    declarations:[Number2Component],
    imports:[Number2RouterModule],
    providers: []
})
export class Number1Module{
}
Enter fullscreen mode Exit fullscreen mode

In Number3.module.ts add the following code,

import { NgModule } from "@angular/core";
import { Number3RouterModule } from "./Number3-routing.module";
import { Number3Component } from "./number3.component";
@NgModule({
    declarations:[Number3Component],
    imports:[Number3RouterModule],
    providers: []
})
export class Number3Module{
}
Enter fullscreen mode Exit fullscreen mode

Step-7 : Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
  {
    path: 'number1',
    loadChildren: () => import('../app/number1/Number1.module').then(x => x.Number1Module)
 },
 {
  path: 'number2',
  loadChildren: () => import('../app/number2/Number2.module').then(x => x.Number2Module)
},
{
  path: 'number3',
  loadChildren: () => import('../app/number3/Number3.module').then(x => x.Number3Module)
},
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers:[]
})
export class AppRoutingModule { }
Enter fullscreen mode Exit fullscreen mode

For your reference, https://stackoverflow.com/a/70354559/16487734
app-routing-module
We will define child modules in loadChildren attribute defining imports and each independent module’s name and its path.

Step-8 : Add routing links to Route HTML page, In app.component.html add the following,

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
  <button><a [routerLink]="['/number1']" routerLinkActive="router-link-active" >Number One</a></button><span></span>
  <button><a [routerLink]="['/number2']" routerLinkActive="router-link-active" >Number Two</a></button><span></span>
  <button><a [routerLink]="['/number3']" routerLinkActive="router-link-active" >Number Three</a></button>
</div>
<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

Now run the application using ng serve

Output:
Image description
You can check the working of this lazy loading by inspecting, To do so, press Ctrl+shift+I. Now under Networks tab you can see the components are not loaded initially.
output
Now if you click on to Number one component button, that component alone will get loaded,
component one

If you click on Number two component buttton, that component will get loaded,
component two

Summary:

It actually reduces the memory occupied by loading only the required resources and it is applied in large applications. Components are loaded after we click on the link, they are not loaded on application initialization or app start. I hope this article would be helpful for you with example and simple definitions.

                      **Thank you! 😎**
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dhanush9952 profile image
Dhanush

Comment if you find this article useful.