Skip to main content

Front-End Development

A Guide to Lazy Loading in Angular

Pexels Pixabay 221185

Lazy loading should be considered for large applications with numerous routes. Sometimes, optimizing performance may risk delivering a better user experience.

Using the technique known as “lazy loading,” the browser loads only the modules or parts that are required for the particular scenario. All the modules will not be loaded except the active route. This technique achieves lower initial bundle sizes and contributes to faster load times.

Generally, when we start the application by default, NgModules are eagerly loaded. It means that as soon as all the NgModules will load, whether that is necessary or not.

Use loadChildren (instead of component) in the AppRoutingModule routes configuration to lazy load Angular modules.

const routes: Routes = [
    {
      path: "items",
      loadChildren: () =>
        import("./items/items.module").then((m) => m.ItemsModule),
    },
  ];

Steps to Implement Lazy Loading in Angular

  1. Create a feature module with a routing file
  2. Create Components
  3. Add Route for Components
  4. Add Navigation Links
  5. Implement Lazy Loading

1. Create a Feature Module with a Routing File

Create a new angular application or in your existing application, here we are going to create a new Admin module. To create the module, we’ll use the Angular cli command. We can create a module with modules in the Angular application using the command that Angular provides. Thus, we’ll use the following command to create the admin module:

ng g module admin --routing

When we successfully execute the above command, we will create files like this:

src/app/admin/admin.module.ts
src/app/admin/admin-routing.module.ts

 

2. Create Components

Let’s create the Components for Modules. The following command will create a component for the admin module. Thus, we will create three components—home, user, and post—in our admin module.

ng g component admin/admin
ng g component admin/user
ng g component admin/post

 

3. Add Route for Components

Here, the route will be added using the created component. After that, we will use our file named admin-routing module and update it.

src/app/admin/admin-routing.module.ts

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { AdminComponent } from "./home/home.component";
import { UserComponent } from "./user/user.component";
import { PostComponent } from "./post/post.component";

const routes: Routes = [
 { path: "", component: AdminComponent },
 { path: "user", component: UserComponent },
 { path: "post", component: PostComponent },
];

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

export class AdminRoutingModule {}

 

4. Add Navigation Links

Now, we will add links to the app component’s HTML file. We will use route-outlet to add all route’s links.

src/app/app.component.html

<div class="container">
 <nav>
  <ul>
   <li>
    <a href="#home" routerLink="/admin">
      Admin
    </a>
   </li>
   <li>
    <a href="#user" routerLink="/admin/user">
      User
    </a>
   </li>
   <li>
     <a href="#post" routerLink="/admin/post">
      Post
     </a>
   </li>
  </ul>
 </nav>
</div>

 

5. Implement Lazy Loading

Now, Import App RoutingModule to the module.ts file. Using the following way:

src/app/app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
 declarations: [AppComponent],
 imports: [BrowserModule, AppRoutingModule],
 providers: [],
 bootstrap: [AppComponent],
})

export class AppModule {}

Make necessary changes in app-routing.module.ts.

Here, we will load the module lazily using loadChildren.

app-routing.module.ts

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { HomeComponent } from "./home/home.component";

const routes: Routes = [
 {
  path: "admin",
  loadChildren: () =>
  import("./module/admin.module").then((m) => m.AdminModule),
 },
 {
  path: "other",
  loadChildren: () =>
  import("./module/other.module").then((m) => m.OtherModule),
 },
 {
  path: "",
  component: HomeComponent,
 },
];

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

export class AppRoutingModule {}

Now, our above code is ready to run. To run the code, use the following command:

ng serve

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Pravin Dhodare

Pravin Dhodare is a front-end developer with over five years of experience and has been a technical consultant for the past three years. Pravin has worked with various UI frameworks and is constantly looking to improve his knowledge of UI technologies. Outside of work, Pravin enjoys taking photographs, sketching, and gardening.

More from this Author

Follow Us