Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk6 min

Optimizing Images with NgOptimizedImage in Angular

A practical guide to Angular's NgOptimizedImage: opting in with ngSrc, marking the LCP image as priority, preventing layout shift, building responsive srcset with sizes, using fill mode instead of background-image, and when a loader or image CDN helps.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To optimize images in Angular, import NgOptimizedImage from @angular/common, replace each image’s src with ngSrc, declare the image’s size so the browser can reserve space for it, and mark the likely Largest Contentful Paint (LCP) image with priority. Responsive images also need a sizes attribute, and a loader from an image CDN is optional. The directive is an opt-in template feature; it does not edit image files or change their pixels.

What NgOptimizedImage does and does not do

NgOptimizedImage is an Angular template directive. You activate it on an <img> element by using ngSrc instead of src. Once active, Angular controls when the browser starts downloading the image, sets fetch priority and loading behavior, and helps prevent layout shift when the page renders. It does not compress, resize, or convert the source file on its own. Those transformations only happen if you point the directive at an image service that performs them, which is covered in the loaders section below.

As an Amazon Associate I earn from qualifying purchases.

The directive also does not apply to CSS background-image declarations. If your markup currently uses a background image, the pattern Angular recommends is covered in the fill mode section.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up NgOptimizedImage step by step

  1. Import the directive. In a standalone component, add it to the imports array. In an NgModule, add it to the module’s imports.
    import { Component } from '@angular/core';
    import { NgOptimizedImage } from '@angular/common';
    
    @Component({
      selector: 'app-hero',
      imports: [NgOptimizedImage],
      template: `<img ngSrc="hero.jpg" width="1200" height="600" priority>`,
    })
    export class HeroComponent {}
  2. Replace src with ngSrc. The directive has to manage when the browser sees the source. A plain src attribute on the same element bypasses that control, so leave src off once ngSrc is in place.
  3. Declare the image’s size. Add width and height, or use fill with a positioned parent. The choice depends on whether the image has a fixed display size, a responsive width, or fills a container. The mode table below shows each case.
  4. Add sizes for responsive slots. If the rendered width changes with the viewport, add a sizes value that matches the real CSS layout.
  5. Mark the LCP image as priority. Only one or a few images per view should receive this attribute. Details follow in the next section.
  6. Check the rendered output. Confirm in the browser’s developer tools that the image has the expected dimensions and that its requested URL matches what you configured.

Mark the LCP image as priority

Angular’s image optimization guide states: “Always mark the LCP image on your page as priority to prioritize its loading.” Adding priority sets high fetch priority and eager loading for that image, and for server-rendered pages it generates a preload hint for the image.

Identify the LCP image by looking at the largest visible image in the initial view, usually a hero banner or the main product photo. Do not assume one image is the LCP element for every visitor. The element can change with the viewport, so check the layouts your users actually see, especially mobile and desktop versions that display different hero images.

Leave ordinary images alone. Non-priority images are lazy-loaded by default. Switching many images to eager loading removes that benefit without a clear reason and can compete with the LCP image for bandwidth.

<img ngSrc="hero-desktop.jpg" width="1200" height="600" priority>
<img ngSrc="product-photo.jpg" width="400" height="400">

In that example, the hero image receives priority and the product photo keeps the default lazy loading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reserve layout space: fixed, responsive, and fill modes

Layout shift happens when an image loads and pushes other content around. Supplying dimensions lets the browser reserve the image’s box before the file arrives. How you declare those dimensions depends on which of three situations you have.

Mode Attributes to set What width and height mean How srcset is generated Typical use
Fixed size width, height, matching aspect ratio Intended rendered dimensions From the dimensions; sizes is not required Avatars, icons, thumbnails with a set display size
Responsive width, height, and sizes Intrinsic dimensions of the source file From the sizes value and the breakpoint list Content images that change width with the viewport
Fill The fill attribute; omit width and height Not applicable; the parent container sets the box Not stated in the guide Images that must cover or fit a positioned container

For fixed and responsive images, the declared width and height should have the same aspect ratio as the actual file. A mismatch makes the browser reserve the wrong box, which reintroduces the shift the attributes are meant to prevent.

Build a responsive srcset with sizes

For responsive images, the sizes attribute tells the browser how much horizontal space the image will occupy at different viewport widths. Angular uses that value to generate candidate image URLs for the srcset. The value should match the real CSS layout. If your CSS makes the image half the viewport wide on tablets and full width on phones, a matching value is:

<img ngSrc="article-cover.jpg"
     width="1600"
     height="900"
     sizes="(max-width: 768px) 100vw, 50vw">

A sizes value that claims a smaller slot than the image actually occupies makes the browser choose a file that is too small and look soft. A value that claims a larger slot makes it download more pixels than the screen shows.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The guide lists the default responsive breakpoints as 16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, and 3840 pixels. These are the default configuration values in the guide, not measured performance results, and they set which candidate widths are considered when building the set.

Use fill mode instead of CSS background-image

Angular documents replacing a CSS background-image pattern with a positioned container and a child image that uses fill. The steps are:

  1. Create a positioned parent. Give the container position: relative, position: absolute, or position: fixed. Without this, the child image has no reference box to fill.
  2. Add the image with fill. Omit width and height on that element.
    <div class="card-media">
      <img ngSrc="banner.jpg" fill>
    </div>
  3. Style the fit and position. Use object-fit: cover when cropping is acceptable and you want the image to fill the box. Use object-fit: contain when the whole image must stay visible, even if that leaves empty space.

Because the image becomes a real <img> element, the directive can handle its loading and priority like any other image. A background image set in CSS cannot be managed that way.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Optional loaders and image CDNs

An image loader is not required to use NgOptimizedImage. The default generic loader does not change the URL. A loader becomes useful when your image service can generate resized, reformatted, or re-compressed variants on request. In that case, the loader builds transformed URLs with the requested width, format, or quality, and the directive can produce an automatic srcset from them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The guide lists built-in loaders for:

  • Cloudflare Image Resizing
  • Cloudinary
  • ImageKit
  • Imgix
  • Netlify

Each service has its own URL conventions, so the loader only works correctly when it matches the service you actually use. If your image service is not on this list, Angular supports a custom loader. Check the guide for the configuration details of the loader you choose, since they differ by service.

When a loader is in use, the image origin may not be visible in your page markup. In that case, add a preconnect hint manually in the document head so the browser opens the connection early:

<link rel="preconnect" href="https://images.example.com">

Replace the example host with your image service’s origin. Angular’s development-mode warnings can flag a missing preconnect hint, so watch the browser console during development.

Version and availability

The current Angular guide and API reference are unversioned. The guide states that NgOptimizedImage became stable in Angular 15 and was backported as stable to versions 13.4.0 and 14.3.0. Before copying an example, check the Angular version in your project’s package.json and confirm the documentation matches that version. The API reference is at angular.dev/api/common/NgOptimizedImage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting checklist

  • The image still loads late. Confirm ngSrc is used rather than src, and that the LCP image has priority.
  • The page shifts while images load. Check that width and height are present for fixed and responsive images and match the file’s aspect ratio. For fill mode, check that the parent is positioned.
  • The browser picks an odd file size. Compare the sizes value with the image’s rendered width in the layout at several viewport widths.
  • A fill image does not appear. Confirm the container has position: relative, absolute, or fixed and has a height of its own.
  • Transformed URLs return errors. Verify that the loader matches the image service and that the origin in the URL is correct.
  • A CSS background image is not optimized. This is expected. Move it into an <img> element inside a positioned container, as described above.

Performance gains from these changes depend on your source image sizes, responsive layout, which element is the LCP, CDN behavior, and whether the page is server-rendered. Measure the result on your own pages rather than relying on a general figure.

“

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.