Angular NgOptimizedImage Directive.

Angular NgOptimizedImage Directive

Angular NgOptimizedImage Directive ensures that the loading of the Largest Contentful Paint (LCP) image is prioritized by:

  • Automatically setting the fetchpriority attribute on the <img> tag
  • Lazy loading non-priority images by default
  • Asserting that there is a corresponding preconnect link tag in the document head

To get more details about this topic please follow this link to their official website.

Step 1: import the NgOptimizedImage directive.

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

// Include it into the necessary NgModule
@NgModule({
  imports: [NgOptimizedImage],
})
class AppModule {}

// ... or a standalone Component
@Component({
  standalone: true
  imports: [NgOptimizedImage],
})
class MyStandaloneComponent {}

Step 2: configure a loader.
To use the default loader: The URL returned by the loader will always match the value of “src” and esource URL and the value of the rawSrc attribute will be used as is.

For the existing loader for a third-party image service: add the provider factory for your chosen service to the providers array.
Example:

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

// Call the function and add the result to the `providers` array:
providers: [
  provideImgixLoader("https://my.base.url/"),
],

The Angular NgOptimizedImage directive provides the following functions:

While using the different image provider, we need create a custom loader function.
To use a custom loader: provide your loader function as a value for the IMAGE_LOADER DI token.

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

// Configure the loader using the `IMAGE_LOADER` token.
providers: [
  {
     provide: IMAGE_LOADER,
     useValue: (config: ImageLoaderConfig) => {
       return `https://example.com/${config.src}-${config.width}.jpg}`;
     }
  },
],

Step 3: update <img> tags in templates to use rawSrc instead of src.

<img rawSrc="logo.png" width="200" height="100">

NgOptimizedImage Methods:

To get to know more about other Angular topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share