Angular 13 Lazy Load Images Tutorial with Example

Angular 13 lazy loading images example. In this tutorial, i am going to show you how to make lazy loading images in an Angular 13 applications.

Angular 13 Lazy Load Images Tutorial with Example

Follow the below given steps to make lazy loading images in angular 13 apps; as follows:

  • Step 1 – Create New Angular App
  • Step 2 – Install Lay Load Library
  • Step 3 – Import Modules in Module.ts File
  • Step 4 – Create Lazy Images Tag in View File
  • Step 5 – Import Components in Component ts File
  • Step 6 – Start the Angular App

Step 1 – Create New Angular App

Run the following command on command prompt to install angular app:

ng new my-new-app

Step 2 – Install Lay Load Library

To install the packages by run the following commands on the terminal:

npm i ng-lazyload-image 

Step 3 – Import Modules in Module.ts File

Go to src/app directory and open app.module.ts file. And then add the following lines of into app.module.ts file:

import { LazyLoadImageModule} from 'ng-lazyload-image';
@NgModule({
  declarations: [...],
  imports: [
.......,
LazyLoadImageModule
     
  ],
  bootstrap: [...]
})
export class AppModule { }

Step 4 – Create Lazy Images Tag in View File

Go to src/app/ and app.component.html and update the following code into it:

<h1>Lazy Load Images</h1>
 
 <div>
   <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">
 </div>
 <div>
   <h2>Responsive Images</h2>
   <img [defaultImage]="defaultImage" [useSrcset]="true" [lazyLoad]="images">
 </div>

Step 5 – Import Components in Component ts File

Go to the src/app directory and open app.component.ts. Then add the following code into component.ts file:

import { Component, VERSION } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  image1="https://images.unsplash.com/photo-1581789164394-810293cd79ce";
  image2="https://images.unsplash.com/photo-1562690868-60bbe7293e94";
  image3="https://images.unsplash.com/photo-1536677813196-8fed27bcecdc"
  image4="https://images.unsplash.com/photo-1599198688091-926a8df3c9be"
  defaultImage = 'https://via.placeholder.com/1000/09f/fff.png';
images = `https://images.unsplash.com/photo-1434725039720-aaad6dd32dfe?fm=jpg 700w,
            https://images.unsplash.com/photo-1437818628339-19ded67ade8e?fm=jpg 1100w`;
 
 
}

Step 6 – Start the Angular App

Run the following command on command prompt to start angular app:

ng serve

Be First to Comment

Leave a Reply

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