Implementing Lazy Loading from Angular ⭐
Tags: javascript, webdev, angular, typescript
Published: 2023-07-25 19:25:43

In this article, I will delve into the implementation process of Lazy Loading in your Angular application. Additionally, I will provide a step-by-step guide on how to do lazy loading for you application.

Before delving into the concept of lazy loading, it is essential to have a clear understanding of routing.

## Angular Routing 
Angular routing is a mechanism that allows you to navigate between different views and components in your Angular application. It helps you build single-page applications ([SPAs](https://www.bloomreach.com/en/blog/2018/what-is-a-single-page-application))by dynamically changing the content displayed on the page without reloading the entire page. Instead of traditional server-side routing, where the server handles navigation and page loads, Angular routing handles navigation on the client-side.

## Why we want Lazy loading to our Application
Lazy loading is essential for optimizing the performance and user experience of your application. Lazy loading allows your application to load only the essential components and modules needed for the initial view. Other part of component are loading if user navigate to through the application. 

## What is Angular Lazy Loading 
Angular provides a powerful feature called "_**Lazy Loading**_" which allows developers to load modules and components on-demand. Lazy loading is technique that allow user to defer loading of certain parts of an angular application. Parts mean certain modules in the application. These modules are loaded dynamically when a user navigate to a route associated with that module, It will reduce the initial load time as well. 

## Implementing Lazy loading to our Angular Application

In your Angular Application you need to create feature modules that encapsulate specific parts of your application. These modules can be loaded independently, and you can specify which modules should be lazy-loaded based on the routes.

**Step 1: Configure Routes**

in side your **app.component.html** template you need to defined the 
`<router-outlet></router-outlet>`

```
<h2>{{title}}</h2>

<button class="btn btn-primary btn-sm" style="margin: 1%;"  routerLink="/users">Users</button>
<button class="btn btn-primary btn-sm" style="margin: 1%;" routerLink="/home">Home</button>

<router-outlet></router-outlet>


```
In your main **app-routing.module.ts**, configure your routes using the **loadChildren** property instead of component. The loadChildren property takes a string that points to the relative path of the lazy-loaded module. 

> _Note:_ LoadChildren is use for lazy loading

```
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path:'',
    redirectTo:'',
    pathMatch:'full'
  },
  {
    path:'users',
    loadChildren:()=> import('./users/users.module').then(m=> m.UsersModule)
  },
  {
    path:'home',
    component:HomeComponent
  }

];

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

```
**Step 2: Create the Users Modules**
To use Lazy Loading, we need to create feature modules that encapsulate specific parts of our application. Each feature module contains its components, services, and other related files.

Open the terminal command and create new component called users component by running the command 

```
ng generate component users
```
Create the users Module(in this case, users.module.ts),

```
ng generate module users
```

> Note: You can create the above module and component manually instead of executing commands

Apart from that, we need to create a feature routing module under the **users-routing.module.ts** file. It should be defined in the **users.module.ts** file under the imports section.

```
  imports: [
    CommonModule,
    UsersRoutingModule
  ]
```

```
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UsersComponent } from './users.component';

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

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

```
 
Here is the folder structure after generating the component and module file


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lr8swth98eq0o1i0rslg.png)

**Step 3: Defined Child routing from the users module**

We need to created two separate component called **users-list** and **users-detail** 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz2xgyqkrk5xdvva6heh.png)

inside the **users.module.ts** we need to defined the two component under  the  **declarations**

```
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UsersComponent } from './users.component';
import { UsersRoutingModule } from './users-routing.module';
import { UsersListComponent } from './users-list/users-list.component';
import { UserDetailComponent } from './users-list/user-detail/user-detail.component';



@NgModule({
  declarations: [
    UsersComponent,
    UsersListComponent,
    UserDetailComponent
  ],
  imports: [
    CommonModule,
    UsersRoutingModule
  ]
})
export class UsersModule { }

```
After that we need to defined the feature child routing under the _users-routing.module.ts_ under the **routes** 

```
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UsersComponent } from './users.component';
import { UsersListComponent } from './users-list/users-list.component';
import { UserDetailComponent } from './users-list/user-detail/user-detail.component';

const routes: Routes = [
  {
    path:'',
    component:UsersComponent
  },
  {
    path:'user-list',
    component:UsersListComponent
  },
  {
    path:'user/:id',
    component:UserDetailComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UsersRoutingModule { }
```
**Step 4: Defined Child routing handling Templates**

Inside the _users.component.html_ file, we have set up navigation for the child routing using the **routerLink** directive. This allows us to navigate to different child routes when the user clicks on specific links. Here's an example of how it's done:

```
<h2>User Component</h2>

<button class="btn btn-warning btn-sm" style="margin: 1%;" [routerLink]="['/users','user-list']">User List</button>
<button class="btn btn-warning btn-sm" style="margin: 1%;" [routerLink]="['/users','user','123']">User Details</button>
```
**For Explanation about above **routerLink****
The [routerLink] attribute can be bound to an expression, and in the `[routerLink]="['/users','user-list']` the expression is ['/users', 'user-list']. This expression is an array of path segments, where each element represents a part of the route URL.

Let's break down the expression:

- **'/users'** : Representing the parent route. It indicates that the navigation will happen relative to the 'users' route

- **'user-list'** : Representing the child route. It indicates that we want to navigate to the 'user-list' route, which is a child route of the 'users' route

**Conclusion:**
Angular Lazy Loading is a powerful feature that optimizes performance by loading modules and components on-demand. By strategically employing Lazy Loading, we can reduce the initial load time and improve the overall user experience

**That’s It!**

Of course you probably want to see this in action. Here’s a working demo for you to fork or play with:

[Demo](https://codesandbox.io/p/github/Mana95/dev-to-angular/lazy-loading?layout=%257B%2522sidebarPanel%2522%253A%2522EXPLORER%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522clkio7trv017v356mdtukdp0k%2522%252C%2522sizes%2522%253A%255B70%252C30%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522clkio7trv017r356m4him7gcy%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522clkio7trv017t356mxpwi6iab%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522clkio7trv017u356m21szuypz%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B50%252C50%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522clkio7trv017r356m4him7gcy%2522%253A%257B%2522id%2522%253A%2522clkio7trv017r356m4him7gcy%2522%252C%2522activeTabId%2522%253A%2522clkiod4ym00hc356msxt4zsnk%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522PR_INFO%2522%252C%2522id%2522%253A%2522clkiod4ym00hc356msxt4zsnk%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%255D%257D%252C%2522clkio7trv017u356m21szuypz%2522%253A%257B%2522id%2522%253A%2522clkio7trv017u356m21szuypz%2522%252C%2522activeTabId%2522%253A%2522clkio910i01of356mb3lukqd4%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522TASK_PORT%2522%252C%2522taskId%2522%253A%2522start%2522%252C%2522port%2522%253A4200%252C%2522id%2522%253A%2522clkio910i01of356mb3lukqd4%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522path%2522%253A%2522%2522%257D%255D%257D%252C%2522clkio7trv017t356mxpwi6iab%2522%253A%257B%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522clkio7trv017s356m2ia0xfpu%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522start%2522%257D%255D%252C%2522id%2522%253A%2522clkio7trv017t356mxpwi6iab%2522%252C%2522activeTabId%2522%253A%2522clkio7trv017s356m2ia0xfpu%2522%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Atrue%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A15%257D)

GitHub : [dev-to-angula lazy loading](https://github.com/Mana95/dev-to-angular)

Thanks for reading the whole story ❤