Angular NgOptimizedImage Example

By Arvind Rai, June 16, 2023
On this page we will learn using NgOptimizedImage directive introduced in Angular 15.
1. Angular NgOptimizedImage helps to adopt performance best practices to load images.
2. The LCP (Largest Contentfull Paint) images are prioritised by setting fetchpriority automatically on img tag, loading other images lazily by default, asserting corresponding preconnect link tag in document head, automatically generating srcset attribute and generating preload hint if app is using SSR.
3. The NgOptimizedImage can use CDN URLs to optimize images.
4. It enforces to use width and height to prevent layout shift and also warns for incorrect values.
5. The NgOptimizedImage is imported from ‘@angular/common’.
 import { NgOptimizedImage } from '@angular/common'; 
The NgOptimizedImage is a standalone directive, so components should import it directly.
6. To enable NgOptimizedImage for our images, use ngSrc, width and height attributes with img tag. We can optionally set a loader to optimize image loading.

Now we will discuss using NgOptimizedImage in our Angular application. To run code, we are using Chrome browser.

1. Using NgOptimizedImage

Find the simple code to use NgOptimizedImage. Use ngSrc, width and height attributes with img tag.
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from "@angular/core";
import { NgOptimizedImage } from '@angular/common';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [
        NgOptimizedImage
    ],
    template: `
       <img ngSrc="assets/images/angular.png" width="283" height="300">
    `
})
export class AppComponent {

}
bootstrapApplication(AppComponent); 
In development mode, Angular warns if width and height attributes are not used. Angular also warns if correct values of width and height are not used.
Now find the output in DOM.
<img ngsrc="assets/images/angular.png" width="283" height="300" ng-reflect-ng-src="assets/images/angular.png" 
ng-reflect-width="283" ng-reflect-height="300" loading="lazy" fetchpriority="auto" ng-img="true" src="assets/images/angular.png”> 
We are testing our code in Chrome browser.

2. Using priority Attribute

Use priority attribute for LCP image to prioritise its loading. The priority attribute applies
1. fetchpriority=high
2. loading=eager
3. automatically generates a preload link element if rendering on the server.

Find the template code snippet.
<img ngSrc="assets/images/angular.png" width="283" height="300" priority> 
Find the code generated in DOM.
<img ngsrc="assets/images/angular.png" width="283" height="300" priority="" ng-reflect-ng-src="assets/images/angular.png" 
ng-reflect-width="283" ng-reflect-height="300" ng-reflect-priority="" loading="eager"
 fetchpriority="high" ng-img="true" src="assets/images/angular.png”> 
In development mode, Angular displays a warning for LCP image if priority attribute is not used.

3. Using fill Attribute

Angular provides fill attribute to fill the containing element with image. The fill attribute is useful for background image. In case of fill attribute, using width and height attributes are not needed.
<img ngSrc="assets/images/background.png" fill> 
To control the image fill to container, use object-fit CSS property.

4. Image Loader

Angular supports three types of loader.
1. Generic loader : The URL returned by the generic loader will always match the value of src. This is the default behavior.
2. Loaders for third-party image services : The URL returned by the this loader  will follow API conventions used by that particular image service.
3. Custom loaders : A custom loader's behavior is defined by its developer.

Find the loaders for third-party image services supported by Angular.
1. provideCloudflareLoader : For Cloudflare Image Resizing.
2. provideCloudinaryLoader : For Cloudinary image service.
3. provideImageKitLoader : For ImageKit image service.
4. provideImgixLoader : For Imgix image service.

The loader for third-party image services needs only base URL of images.
providers: [
    provideImgixLoader('http://localhost:4200/assets/images/')
] 
Find the example with provideImgixLoader.
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from "@angular/core";
import { NgOptimizedImage, provideImgixLoader } from '@angular/common';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [
        NgOptimizedImage
    ],
    providers: [
        provideImgixLoader('http://localhost:4200/assets/images/'),
    ],
    template: `
       <h2>Angular</h2>
       <img ngSrc="angular.png" width="283" height="300">
       <h2>Java</h2>
       <img ngSrc="java.png" width="400" height="400">
       <h2>Spring</h2>
       <img ngSrc="spring.png" width="224" height="225">
    `
})
export class AppComponent {

}
bootstrapApplication(AppComponent); 
Find the print screen of the output.
Angular NgOptimizedImage Example

5. Improve Loading Performance

1. We can add preconnect resource hint for our image origin in the <head> of the document to load LCP image as early as possible.
<link rel="preconnect" href="https://my.cdn.origin" /> 
2. We can defining a srcset attribute to ensure that the browser requests an image at the right size for our user's viewport.
3. If image is of fixed size, then there is no need to set a sizes attribute. A srcset can be generated automatically from the image's width and height attributes with no further input required.
4. If our image should be responsive, then we will need to define a sizes attribute to generate the srcset.
5. To disable srcset generation for single image, use disableOptimizedSrcset attribute.
<img ngSrc="angular.png" width="283" height="300" disableOptimizedSrcset> 
6. By default, images are set as loading=lazy for all images that are not marked priority. We can disable this behaviour by setting loading="eager".
<img ngSrc="angular.png" width="283" height="300" loading="eager"> 

6. Reference

7. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us