Using the NgOptimizedImage directive to implement image loading in Angular

Directive NgOptimizedImage in Angular is responsible for implementing image loading while maintaining high performance. It is available in Angular v14.2.0. The directive is marked as standalone and can be imported into standalone components and modules.

To use it, we must replace the attribute src your image on rawSrc:

import { NgOptimizedImage } from '@angular/common';

  standalone: true,
  imports: [NgOptimizedImage],
  template: `
    <!-- видимая область страницы -->
    <img rawSrc="" width="200" height="300" priority />
    <!-- ниже видимой области страницы -->
    <img rawSrc="" 
        style="margin-top: 300vh" 
        height="300" />`,
export class LoginPageComponent {}

The directive will provide us with the following benefits LCP(Main Content Download Speed):

  • Attribute loading for images below the visible area of ​​the page will be set to lazywhile the attribute loading for images in the visible area of ​​the page will be eager.

  • It guarantees priority for images in the visible area of ​​the page. This means that the value will be set high for attribute fetchpriority. The default value is default.

  • It ensures that images in the visible area of ​​the page will have the appropriate tag. preconnect.

<!doctype html>
<html lang="en">

  <meta charset="utf-8">
  <base href="">
  <!-- 👇🏻 👇🏻 👇🏻 👇🏻 👇🏻 👇🏻 -->
  <link rel="preconnect" href="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="">


  • It ensures that the width and height are set in a way that prevents layout shifts.

The word “guaranteed” means that the directive will warn you if it’s not.

Image uploaders

A loader is a function that generates the corresponding resource URL for a given image file. The default loader returns srcwhich we pass for rawSrc. Angular also provides various loaders for third-party image services:

To use them, we must pass the provider factory for the selected service to the providers array:

import { NgOptimizedImage, provideImgixLoader } from '@angular/common';

  providers: [
    provideImgixLoader("https://my.base.url/", {
      ensurePreconnect: boolean
  bootstrap: [AppComponent]
export class AppModule { }

We can create our own loader by overriding the provider IMAGE_LOADER:

import { ImageLoaderConfig, IMAGE_LOADER, NgOptimizedImage } from '@angular/common';

  providers: [{ 
    provide: IMAGE_LOADER, 
    useValue: (config: ImageLoaderConfig) => { 
      return `${config.src}&width=${config.width}` } 
  bootstrap: [AppComponent]
export class AppModule { }

Additional information about the API:

Similar Posts

Leave a Reply

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