Examples

Here are some common use cases for using the NgOptimizedImage directive with ng-image-optimizer.

Basic Usage

Provide width and height to prevent cumulative layout shift (CLS). The optimizer will automatically scale the image to these dimensions while preserving aspect ratio.

html
<img [ngSrc]="'/hero.webp'" width="1200" height="600" alt="Hero image" />

Fill Mode

When you don't know the exact dimensions beforehand (e.g., responsive grids or hero sections), use the fill attribute. The parent container must have position: relative, position: fixed, or position: absolute.

html
<div style="height: 300px; position: relative;">
  <img [ngSrc]="'/background.avif'" fill style="object-fit: cover;" alt="Background" />
</div>

Priority Loading

For Above the Fold (LCP) images, always add the priority attribute. This ensures the optimizer processes the image synchronously if necessary or queues it first, and Angular adds fetchpriority="high" to the DOM.

html
<img [ngSrc]="'/logo.png'" width="200" height="50" priority alt="Brand logo" />

Custom Quality

Adjust the compression quality (1-100) via loaderParams to override the server's default quality settings for a specific image.

html
<img 
  [ngSrc]="'/photo.jpg'" 
  width="800" 
  height="400" 
  [loaderParams]="{ quality: 80 }" 
  alt="Custom quality" 
/>

Responsive Sizes

Use the sizes attribute to generate responsive srcset values. The optimizer integrates with the server config's deviceSizes and imageSizes.

html
<img 
  [ngSrc]="'/responsive.jpg'" 
  fill
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  alt="Responsive grid image" 
/>

Blur Placeholder

Use the placeholder attribute to display a small, heavily blurred version of the image while the full-resolution image is loading. The server will automatically generate a highly compressed base64 string for this inline placeholder.

html
<img 
  [ngSrc]="'/nature.webp'"
  width="800"
  height="600"
  placeholder
  alt="Placeholder example"
/>