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.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Set up NgOptimizedImage step by step
- Import the directive. In a standalone component, add it to the
importsarray. In an NgModule, add it to the module’simports.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 {} - Replace
srcwithngSrc. The directive has to manage when the browser sees the source. A plainsrcattribute on the same element bypasses that control, so leavesrcoff oncengSrcis in place. - Declare the image’s size. Add
widthandheight, or usefillwith 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. - Add
sizesfor responsive slots. If the rendered width changes with the viewport, add asizesvalue that matches the real CSS layout. - Mark the LCP image as
priority. Only one or a few images per view should receive this attribute. Details follow in the next section. - 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.
#1 Best Overall
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.
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.
Rank #2
| 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.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallRank #3
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:
- Create a positioned parent. Give the container
position: relative,position: absolute, orposition: fixed. Without this, the child image has no reference box to fill. - Add the image with
fill. Omitwidthandheighton that element.<div class="card-media"> <img ngSrc="banner.jpg" fill> </div> - Style the fit and position. Use
object-fit: coverwhen cropping is acceptable and you want the image to fill the box. Useobject-fit: containwhen 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.
Rank #4
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.
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.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Troubleshooting checklist
- The image still loads late. Confirm
ngSrcis used rather thansrc, and that the LCP image haspriority. - The page shifts while images load. Check that
widthandheightare 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
sizesvalue 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, orfixedand 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.
Quick Recap
“
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.




