Angular Snippets

New Image Directive in Angular v15

angular15 image directive

Here is a simple example of how to use the NgOptimizedImage directive. The NgOptimizedImage directive makes it easy to adopt performance best practices for loading images.

Import NgOptimizedImage

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

Enable the directive

To enable the NgOptimizedImage directive, replace your image’s src attribute with ngSrc and to prevent image related layout shifts, NgOptimizedImage requires that you specify a height and width for the image

<img ngSrc="image.jpg" width="300" height="200" />

And if you don’t know the size of the images, you can use the fill attribute to inherit the size of the parent container. For the “fill” image to render properly, its parent element must be styled with position: "relative", position: "fixed", or position: "absolute".

<img ngSrc="image.jpg" fill />

Back to snippets