How can be implement lazy loading?

 To implement lazy loading in Angular, you need to configure the routing system in a way that allows certain feature modules to be loaded only when they are accessed via specific routes. This reduces the initial load time of the application, as only the necessary parts of the application are loaded at first, and others are loaded dynamically when required.

Here's how you can implement lazy loading in an Angular application step by step:


Step-by-Step Guide to Implement Lazy Loading

Step 1: Create a New Angular Application (if not already done)

If you don’t have an Angular application yet, you can create one using Angular CLI:

bash

ng new angular-lazy-loading-app cd angular-lazy-loading-app

Ensure that you select Yes for routing when asked during project creation.


Step 2: Create Feature Modules

You need to create feature modules for the sections of the application that you want to load lazily. Feature modules are typically organized around specific application areas (e.g., admin, products, user-profile, etc.).

Let's create two feature modules: AdminModule and ProductsModule.

Run the following commands to generate the feature modules:

bash

ng generate module admin --route admin --module app.module ng generate module products --route products --module app.module
  • The --route flag automatically sets up routing for the feature modules.
  • The --module app.module flag links these feature modules to the AppModule.

This will generate:

  • admin.module.ts: The feature module for the Admin section.
  • products.module.ts: The feature module for the Products section.

Step 3: Define Routes in Feature Modules

Each of the generated feature modules will have its own routing configuration file, such as admin-routing.module.ts and products-routing.module.ts.

Here is how you can set up the routing in admin-routing.module.ts:

typescript

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminComponent } from './admin/admin.component'; const routes: Routes = [ { path: '', component: AdminComponent } // Default route for the Admin module ]; @NgModule({ imports: [RouterModule.forChild(routes)], // Use forChild for feature modules exports: [RouterModule] }) export class AdminRoutingModule { }

Repeat a similar configuration for products-routing.module.ts:

typescript

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProductsComponent } from './products/products.component'; const routes: Routes = [ { path: '', component: ProductsComponent } // Default route for the Products module ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProductsRoutingModule { }

Step 4: Configure Lazy Loading in app-routing.module.ts

Now, go to the main routing file, app-routing.module.ts, and set up the lazy loading for the two feature modules (AdminModule and ProductsModule).

Replace the content of app-routing.module.ts with:

typescript

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // Lazy-loaded routes const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // Redirect to Home by default { path: 'home', component: HomeComponent }, // Lazy loading feature modules { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }, { path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

Here’s how it works:

  • loadChildren: This is the key to lazy loading. When the user navigates to /admin or /products, Angular will load the respective modules asynchronously.
  • import('./admin/admin.module').then(m => m.AdminModule): This is an ES6 dynamic import that tells Angular to load the module only when the route is accessed.

Step 5: Set Up Feature Module Components

In the feature modules (admin.module.ts and products.module.ts), add components that will be displayed when the respective routes are visited.

  1. Create AdminComponent:
bash

ng generate component admin/admin

In admin.component.html:

html

<h1>Admin Dashboard</h1> <p>Welcome to the Admin section!</p>
  1. Create ProductsComponent:
bash

ng generate component products/products

In products.component.html:

html

<h1>Product List</h1> <p>Browse the product catalog!</p>

Step 6: Add Navigation Links to the Main Template (app.component.html)

In your main component template, set up navigation links to the lazy-loaded routes (/admin and /products).

Edit app.component.html:

html

<nav> <ul> <li><a routerLink="/home">Home</a></li> <li><a routerLink="/admin">Admin</a></li> <li><a routerLink="/products">Products</a></li> </ul> </nav> <router-outlet></router-outlet> <!-- Where lazy-loaded components will be rendered -->

Step 7: Update app.module.ts

Make sure that all feature modules are correctly imported into your app.module.ts, but don’t import the feature modules directly. The lazy-loaded modules will be loaded when the user navigates to their corresponding routes.

typescript

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; // Import AppRoutingModule @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AppRoutingModule // Import the routing module with lazy loading config ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Step 8: Run the Application

Now, run your application to test lazy loading:

bash

ng serve

Navigate to:

  • /admin: The AdminModule will be loaded lazily.
  • /products: The ProductsModule will be loaded lazily.
  • /home: The home page will be shown as configured.

Use your browser's developer tools to observe that the JavaScript bundle for AdminModule and ProductsModule is only loaded when you navigate to the respective routes.


Key Points of Lazy Loading

  1. Modularization: Lazy loading helps in breaking the app into smaller modules. Only the necessary parts are loaded when needed, which helps with scalability and performance.

  2. Asynchronous Loading: Lazy loading is implemented using dynamic imports (import()). This enables the browser to fetch and load the required module when the user navigates to a specific route.

  3. Improved Performance: By loading only what’s necessary upfront, the initial page load is faster, making the app feel more responsive, especially for large applications.


Conclusion

Lazy loading in Angular allows you to improve the performance of your application by loading feature modules only when they are needed. It is achieved by:

  • Creating feature modules.
  • Configuring routes with loadChildren in the main AppRoutingModule.
  • Using dynamic imports to load modules asynchronously.

This makes your Angular app more efficient, especially as it scales.

Comments

Popular posts from this blog

Is there a compatibility list for Angular / Angular-CLI and Node.js?

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

How to resolve CORS issue in Angular 12?