The Angular team has always focused on improving the framework by making everything faster, from the compiler to our runtime code that gets optimized, minified, and tree-shaked.
The Image optimization directive was added to Angular 15 in that same spirit.
What it does:
- Intelligent lazy loading: Images invisible to the user on page load are loaded later when the user scrolls down to that page section.
- Prioritization of critical images: Load the essential images first (header banner, for instance)
- Optimized configuration for popular image tooling: If you’re using a CDN, the directive will automatically pick the proper image size from that CDN, optimizing download sizes based on how many pixels of that image will be displayed on the screen.
- Built-in errors and warnings: Besides the above built-in optimizations, the directive also has built-in checks to ensure developers have followed the recommended best practices in the image markup.
All you have to do to get all these benefits is to use the ngSrc
attribute instead of just src
:
For CDN optimization, you can use one the 4 existing providers (or create your own) so that the proper image size is always requested. In my example, I use the Imgix CDN, so my config looks like this:
From that information alone, we can tell that Angular was able to generate the proper image URLs to fetch the smallest image possible to fit our div – no more downloading of a 2000 x 1000 pixels image if all you need is 200 x 100:
The NgOptimizedImage
directive is part of the @angular/common
module, just like ngFor
and ngIf
, so it’s already part of your toolkit if you use those directives.
It can also be used as a standalone directive without importing CommonModule
. My example is on Stackblitz here. The official documentation and more information about that directive can be found here.