Lazy loading in Angular with example
Tags: angular, typescript, lazyloading, webdev
Published: 2022-05-15 07:02:42

## 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,

```typescript
> ng new LazyDemo
```
![create new application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m5abw48ey5i5q0jtapy.png)
make sure to allow routing when creating new project or you can simply use the command : **> ng new LazyDemo — routing**

```typescript
> cd LazyDemo
```
**Step-2 :** Create 3 components or any numbers of your choice just for demo purpose I’m creating 3 components,

```typescript
> ng generate component Number1
  ng generate component Number2
  ng generate component Number3
```
  
![create 3 components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cdieeah0s82uoybc1o0f.png)
 
**Step-3 :** Create respective module files in each of the component folders,

```typescript
> Number1.module.ts
  Number2.module.ts
  Number3.module.ts
```

Now our file/folder structure will look like this,
![Folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moty19edezx4pxvl8ekw.png)
**Step-4 :** Create a respective router module file in each component folder, 

```typescript
> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts
```
![Number1-routing.module.ts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/606mkbih4bwefk1e7aoo.png)
**Step-5 :** Import the Router Module in the main application module app.module.ts, 

```typescript
import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],
```
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,

```typescript
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{}
```
Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzneq3zqmz75bwpn1cby.png)
Similarly add the codes in **Number2-routing.module.ts** and **Number3-routing.module.ts**.

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

```typescript
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{}
```
In **Number3-routing.module.ts** add the following codes,

```typescript
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{}
```
In **Number1.module.ts** add following code,

```typescript
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{
}
```
![number1.module.ts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jj6zi9x1tniogq3mow58.png)
Similarly add same in the other two files Number2.module.ts and Number3.module.ts,

In **Number2.module.ts** add the following code, 

```typescript
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{
}
```
In **Number3.module.ts** add the following code,

```typescript
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{
}
```
**Step-7 :** Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,

```typescript
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 { }
```
For your reference, [https://stackoverflow.com/a/70354559/16487734](https://stackoverflow.com/a/70354559/16487734)
![app-routing-module](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mkznphdzyg2mwtbkpr27.png)
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, 

```html
<!--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>
```
Now run the application using **ng serve**

**Output:**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cie6lv8c8h41fbkmbh1.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jckh9pgqbcigpeqdz8cr.png)
Now if you click on to **Number one** component button, that component alone will get loaded, 
![component one](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e36wt306pd87t570av1h.png)

If you click on **Number two** component buttton, that component will get loaded,
 ![component two](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qyu166d28fdzm7xkevka.png)
## 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! 😎**