DEV Community

Cover image for Implementing Lazy Loading from Angular ⭐
Manoj Prasanna  πŸš€
Manoj Prasanna πŸš€

Posted on

Implementing Lazy Loading from Angular ⭐

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)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>


Enter fullscreen mode Exit fullscreen mode

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 { }

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Create the users Module(in this case, users.module.ts),

ng generate module users
Enter fullscreen mode Exit fullscreen mode

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
  ]
Enter fullscreen mode Exit fullscreen mode
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 { }

Enter fullscreen mode Exit fullscreen mode

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

Image description

Step 3: Defined Child routing from the users module

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

Image description

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 { }

Enter fullscreen mode Exit fullscreen mode

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 { }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

GitHub : dev-to-angula lazy loading

Thanks for reading the whole story ❀

Top comments (1)

Collapse
 
manojmj profile image
Manojkumar

nice content demo is not working for me