How To Implement Lazy Loading Module In Angular 9

In this article, we will learn how to implement the Lazy Loading Module in Angular 9.

In an Angular application, NgModules are eagerly loaded. As soon as the application loads, all the NgModules get loads, whether it’s necessary or not. The Lazy Loading feature introduced in Angular, to load NgModules as needed. To decrease load times, Lazy Loading helps keep the initial bundle size smaller.

To implement a Lazy Loading feature module in Angular application:

Set up an Angular application

Enter the following command to create an app named product-app:

ng new product-app

Creating a Feature Module

Enter the following command to create a feature module named dashboard:

ng g module admin

Enter the following command to create components inside the feature module:

ng g c admin/profile
ng g c admin/dashboard

Set Routing Components Inside the Feature Module

Open the admin.module.ts file and add the code in it.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ProfileComponent } from './profile/profile.component';

const routes: Routes = [
  { path: '', component: DashboardComponent },
  { path: 'profile', component: ProfileComponent }
];

@NgModule({
  declarations: [DashboardComponent, ProfileComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class AdminModule { }

Imports and Route Configuration

Open the app-routing.module.ts file and add the code in it.

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

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

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

loadChildren() function uses the browser’s built-in import(‘…’) syntax for dynamic imports. The import path is the relative path to the module.

– – –

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Separate Development And Production URL In Angular 9

Submit a Comment

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

Subscribe

Select Categories