Lazy Loading Images in Angular: Improve Performance and User Experience
Lazy loading images in Angular can help improve the performance of your application by only loading images when they are needed. Here are the steps to implement lazy loading of images in Angular:
- Install the ng-lazyload-image package using npm or yarn:
npm install ng-lazyload-image
or
yarn add ng-lazyload-image
2. Import the LazyLoadImageModule into your app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LazyLoadImageModule } from 'ng-lazyload-image';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LazyLoadImageModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. In your HTML template, use the lazyLoad
directive on the img
tag and set the src
attribute to the URL of a placeholder image that will be displayed until the actual image is loaded:
<img [lazyLoad]="imageUrl" src="placeholder.jpg" alt="Description of the image">
4. In your component, define the imageUrl
property to be the URL of the actual image:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<img [lazyLoad]="imageUrl" src="placeholder.jpg" alt="Description of the image">
`,
})
export class AppComponent {
imageUrl = 'https://example.com/image.jpg';
}
That’s it! Now the actual image will only be loaded when the user scrolls to the img
tag, and the placeholder image will be displayed until then.