Lazy Load Images in Angular

In this article, we’ll learn how to implement lazy loading images in an Angular application.
Lazy Loading: Lazy Loading Images is a technique, where we delay the loading of images until we need them. For example, Load only those images which are display view. The images below the display are loaded only when the user scrolls to that location. This helps to load the page quickly. Using this we improvement of the page loading.
For Lazy Loading we used “ng-lazyload-image” plugin for implementing lazz loading imagess.
Let’s create a new project to demo for lazy loading images. For that, first, we need an angular project to create a project run below command.

ng new lazy-loading-images-demo

“lazy-loading-images-demo” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd lazy-loading-images-demo”. To Run angular applications, it required to run “ng serve”.
After that, we need to install the “ng-lazyload-image” npm package in our application. run below command to install.

npm i ng-lazyload-image

After installing the module we need to add “LazyLoadImageModule” in our app.module.ts file.
Display in the below code.

import { LazyLoadImageModule} from 'ng-lazyload-image';

  declarations: [...],
  imports: [
  bootstrap: [...]

export class AppModule { }

After adding module in the module file now we can use “lazyLoad” directive for the property binding.

<img height="500" width="500" [lazyLoad]="image">

Let’s take an emple for when scroll images loading. for that add below code in app.component.ts & app.module.html file.

import { Component, VERSION } from '@angular/core';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent  {
  name = 'Angular ' + VERSION.major;


  defaultImage = '';

images = ` 700w,

<h1>Lazy Load Images</h1>
   <img height="700" width="700" [lazyLoad]="image1">
  <img height="700" width="700" [lazyLoad]="image2">
  <img height="700" width="700" [lazyLoad]="image3">
  <img height="700" width="700" [lazyLoad]="image4">

   <h2>Responsive Images</h2>
   <img [defaultImage]="defaultImage" [useSrcset]="true" [lazyLoad]="images">


Responsive Images

For display responsive images use the useSrcSet property

<img [defaultImage]="defaultImage" [lazyLoad]="images" [useSrcset]="true" />

Background Image When loading image

<img [backgroundImage]="defaultImage" [lazyLoad]="images" [useSrcset]="true" />


To get a better understanding of what is happening you can pass [debug]=”true” which will output some debug information in the web console.

<img [debug]="true" [defaultImage]="defaultImage" [lazyLoad]="images" [useSrcset]="true" />


Below is the full embeded code for the paging . you can easily used in your application.

Spread the love
  • 9
  • 2