Welcome folks today in this blog post we will be loading
images in lazy-load
manner on mouse scroll
using ng-lazyload-image
library in typescript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command
ng new sampleapp
And after that you need to install the below libraries using the below command as shown below
npm i ng-lazyload-image
After that you will see the below directory structure
of the app as shown below
And now first of all we need to go to app.module.ts
file and copy paste the following code
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { LazyLoadImageModule } from 'ng-lazyload-image'; @NgModule({ imports: [ BrowserModule, FormsModule, LazyLoadImageModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } |
And then we need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<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> |
As you can see we are having the img
loading inside the img
tags and inside that we are providing the width
property and then we are providing the [lazyLoad]
Attribute to lazy load the image.
And now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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`; } |