diff --git a/aio/content/guide/image-directive.md b/aio/content/guide/image-directive.md
index 06ce9d3dc3f385..ddca51c255bc8c 100644
--- a/aio/content/guide/image-directive.md
+++ b/aio/content/guide/image-directive.md
@@ -89,7 +89,40 @@ You can typically fix this by adding `height: auto` or `width: auto` to your ima
### Handling `srcset` attributes
-If your `` tag defines a `srcset` attribute, replace it with `ngSrcset`.
+Defining a [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) ensures that the browser requests an image at the right size for your user's viewport, so it doesn't waste time downloading an image that's too large. 'NgOptimizedImage' generates an appropriate `srcset` for the image, based on the presence and value of the [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) on the image tag.
+
+#### Fixed-size images
+
+If your image should be "fixed" in size (i.e. the same size across devices, except for [pixel density](https://web.dev/codelab-density-descriptors/)), there is no need to set a `sizes` attribute. A `srcset` can be generated automatically from the image's width and height attributes with no further input required.
+
+Example srcset generated: ``
+
+#### Responsive images
+
+If your image should be responsive (i.e. grow and shrink according to viewport size), then you will need to define a [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) to generate the `srcset`.
+
+If you haven't used `sizes` before, a good place to start is to set it based on viewport width. For example, if your CSS causes the image to fill 100% of viewport width, set `sizes` to `100vw` and the browser will select the image in the `srcset` that is closest to the viewport width (after accounting for pixel density). If your image is only likely to take up half the screen (ex: in a sidebar), set `sizes` to `50vw` to ensure the browser selects a smaller image. And so on.
+
+If you find that the above does not cover your desired image behavior, see the documentation on [advanced sizes values](#advanced-sizes-values).
+
+By default, the responsive breakpoints are:
+
+`[16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840]`
+
+If you would like to customize these breakpoints, you can do so using the `IMAGE_CONFIG` provider:
+
+
+providers: [
+ {
+ provide: IMAGE_CONFIG,
+ useValue: {
+ breakpoints: [16, 48, 96, 128, 384, 640, 750, 828, 1080, 1200, 1920]
+ }
+ },
+],
+
+
+If you would like to manually define a `srcset` attribute, you can provide your own directly, or use the `ngSrcset` attribute:
@@ -97,9 +130,7 @@ If your `` tag defines a `srcset` attribute, replace it with `ngSrcset`.
-If the `ngSrcset` attribute is present, `NgOptimizedImage` generates and sets the [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) using the configured image loader. Do not include image file names in `ngSrcset` - the directive infers this information from `ngSrc`. The directive supports both width descriptors (e.g. `100w`) and density descriptors (e.g. `1x`) are supported.
-
-You can also use `ngSrcset` with the standard image [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes).
+If the `ngSrcset` attribute is present, `NgOptimizedImage` generates and sets the `srcset` using the configured image loader. Do not include image file names in `ngSrcset` - the directive infers this information from `ngSrc`. The directive supports both width descriptors (e.g. `100w`) and density descriptors (e.g. `1x`) are supported.
@@ -107,6 +138,16 @@ You can also use `ngSrcset` with the standard image [`sizes` attribute](https://
+### Disabling automatic srcset generation
+
+To disable srcset generation for a single image, you can add the `unoptimized` attribute on the image:
+
+
+
+<img ngSrc="about.jpg" unoptimized>
+
+
+
### Disabling image lazy loading
By default, `NgOptimizedImage` sets `loading=lazy` for all images that are not marked `priority`. You can disable this behavior for non-priority images by setting the `loading` attribute. This attribute accepts values: `eager`, `auto`, and `lazy`. [See the documentation for the standard image `loading` attribute for details](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading#value).
@@ -117,6 +158,20 @@ By default, `NgOptimizedImage` sets `loading=lazy` for all images that are not m
+### Advanced 'sizes' values
+
+You may want to have images displayed at varying widths on differently-sized screens. A common example of this pattern is a grid- or column-based layout that renders a single column on mobile devices, and two columns on larger devices. You can capture this behavior in the `sizes` attribute, using a "media query" syntax, such as the following:
+
+
+
+<img ngSrc="cat.jpg" width="400" height="200" sizes="(max-width: 768px) 100vw, 50vw">
+
+
+
+The `sizes` attribute in the above example says "I expect this image to be 100 percent of the screen width on devices under 768px wide. Otherwise, I expect it to be 50 percent of the screen width.
+
+For additional information about the `sizes` attribute, see [web.dev](https://web.dev/learn/design/responsive-images/#sizes) or [mdn](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes).
+
diff --git a/goldens/public-api/common/index.md b/goldens/public-api/common/index.md
index 368263a16a3943..c30f4b3690658f 100644
--- a/goldens/public-api/common/index.md
+++ b/goldens/public-api/common/index.md
@@ -563,11 +563,15 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
get priority(): boolean;
// @deprecated
set rawSrc(value: string);
+ sizes?: string;
+ set unoptimized(value: string | boolean | undefined);
+ // (undocumented)
+ get unoptimized(): boolean;
set width(value: string | number | undefined);
// (undocumented)
get width(): number | undefined;
// (undocumented)
- static ɵdir: i0.ɵɵDirectiveDeclaration;
+ static ɵdir: i0.ɵɵDirectiveDeclaration;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration;
}
diff --git a/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts b/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts
index fca335c95e4fa8..5f7da46b024f28 100644
--- a/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts
+++ b/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
-import {Directive, ElementRef, inject, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core';
+import {Directive, ElementRef, inject, InjectionToken, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../../errors';
@@ -49,6 +49,15 @@ export const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
*/
export const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
+/**
+ * Used in generating automatic density-based srcsets
+ */
+const DENSITY_SRCSET_MULTIPLIERS = [1, 2];
+
+/**
+ * Used to determine which breakpoints to use on full-width images
+ */
+const VIEWPORT_BREAKPOINT_CUTOFF = 640;
/**
* Used to determine whether two aspect ratios are similar in value.
*/
@@ -61,6 +70,34 @@ const ASPECT_RATIO_TOLERANCE = .1;
*/
const OVERSIZED_IMAGE_TOLERANCE = 1000;
+/**
+ * A configuration object for the NgOptimizedImage directive. Contains:
+ * - viewportBreakpoints: An array of integer breakpoints used to generate
+ * srcsets for responsive images.
+ * - subViewportBreakpoints: An array of smaller breakpoints. Added to the
+ * srcset when `sizes` indicates a sub-full-width responsive image.
+ *
+ * Learn more about the responsive image configuration in [the NgOptimizedImage
+ * guide](guide/image-directive).
+ * @developerPreview
+ */
+export type ImageConfig = {
+ breakpoints?: number[]
+};
+
+const defaultConfig: ImageConfig = {
+ breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
+};
+
+/**
+ * Injection token that configures the image optimized image functionality.
+ *
+ * @see `NgOptimizedImage`
+ * @developerPreview
+ */
+export const IMAGE_CONFIG = new InjectionToken(
+ 'ImageConfig', {providedIn: 'root', factory: () => defaultConfig});
+
/**
* Directive that improves image loading performance by enforcing best practices.
*
@@ -72,6 +109,7 @@ const OVERSIZED_IMAGE_TOLERANCE = 1000;
*
* In addition, the directive:
* - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided
+ * - Automatically generates a srcset
* - Requires that `width` and `height` are set
* - Warns if `width` or `height` have been set incorrectly
* - Warns if the image will be visually distorted when rendered
@@ -165,6 +203,7 @@ const OVERSIZED_IMAGE_TOLERANCE = 1000;
})
export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
private imageLoader = inject(IMAGE_LOADER);
+ private config: ImageConfig = processConfig(inject(IMAGE_CONFIG));
private renderer = inject(Renderer2);
private imgElement: HTMLImageElement = inject(ElementRef).nativeElement;
private injector = inject(Injector);
@@ -223,6 +262,12 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
*/
@Input() ngSrcset!: string;
+ /**
+ * The base `sizes` attribute passed through to the `` element.
+ * Providing sizes causes the image to create an automatic responsive srcset.
+ */
+ @Input() sizes?: string;
+
/**
* The intrinsic width of the image in pixels.
*/
@@ -269,6 +314,18 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
}
private _priority = false;
+ /**
+ * Disables automatic srcset generation for this image.
+ */
+ @Input()
+ set unoptimized(value: string|boolean|undefined) {
+ this._unoptimized = inputToBoolean(value);
+ }
+ get unoptimized(): boolean {
+ return this._unoptimized;
+ }
+ private _unoptimized = false;
+
/**
* Value of the `src` attribute if set on the host `` element.
* This input is exclusively read to assert that `src` is not set in conflict
@@ -290,12 +347,17 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
assertValidNgSrcset(this, this.ngSrcset);
assertNoConflictingSrc(this);
- assertNoConflictingSrcset(this);
+ if (this.ngSrcset) {
+ assertNoConflictingSrcset(this);
+ }
assertNotBase64Image(this);
assertNotBlobUrl(this);
assertNonEmptyWidthAndHeight(this);
assertValidLoadingInput(this);
assertNoImageDistortion(this, this.imgElement, this.renderer);
+ if (!this.srcset) {
+ assertNoComplexSizes(this);
+ }
if (this.priority) {
const checker = this.injector.get(PreconnectLinkChecker);
checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
@@ -325,8 +387,13 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
// The `src` and `srcset` attributes should be set last since other attributes
// could affect the image's loading behavior.
this.setHostAttribute('src', this.getRewrittenSrc());
+ if (this.sizes) {
+ this.setHostAttribute('sizes', this.sizes);
+ }
if (this.ngSrcset) {
this.setHostAttribute('srcset', this.getRewrittenSrcset());
+ } else if (!this._unoptimized && !this.srcset) {
+ this.setHostAttribute('srcset', this.getAutomaticSrcset());
}
}
@@ -370,6 +437,36 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
return finalSrcs.join(', ');
}
+ private getAutomaticSrcset(): string {
+ if (this.sizes) {
+ return this.getResponsiveSrcset();
+ } else {
+ return this.getFixedSrcset();
+ }
+ }
+
+ private getResponsiveSrcset(): string {
+ const {breakpoints} = this.config;
+
+ let filteredBreakpoints = breakpoints!;
+ if (this.sizes?.trim() === '100vw') {
+ // Since this is a full-screen-width image, our srcset only needs to include
+ // breakpoints with full viewport widths.
+ filteredBreakpoints = breakpoints!.filter(bp => bp >= VIEWPORT_BREAKPOINT_CUTOFF);
+ }
+
+ const finalSrcs =
+ filteredBreakpoints.map(bp => `${this.imageLoader({src: this.ngSrc, width: bp})} ${bp}w`);
+ return finalSrcs.join(', ');
+ }
+
+ private getFixedSrcset(): string {
+ const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map(
+ multiplier => `${this.imageLoader({src: this.ngSrc, width: this.width! * multiplier})} ${
+ multiplier}x`);
+ return finalSrcs.join(', ');
+ }
+
ngOnDestroy() {
if (ngDevMode) {
if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) {
@@ -399,6 +496,16 @@ function inputToBoolean(value: unknown): boolean {
return value != null && `${value}` !== 'false';
}
+/**
+ * Sorts provided config breakpoints and uses defaults.
+ */
+function processConfig(config: ImageConfig): ImageConfig {
+ let sortedBreakpoints: {breakpoints?: number[]} = {};
+ if (config.breakpoints) {
+ sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);
+ }
+ return Object.assign({}, defaultConfig, config, sortedBreakpoints);
+}
/***** Assert functions *****/
@@ -448,6 +555,23 @@ function assertNotBase64Image(dir: NgOptimizedImage) {
}
}
+/**
+ * Verifies that the 'sizes' only includes responsive values.
+ */
+function assertNoComplexSizes(dir: NgOptimizedImage) {
+ let sizes = dir.sizes;
+ if (sizes) {
+ if (sizes.match(/((\)|,)\s|^)\d+px/)) {
+ throw new RuntimeError(
+ RuntimeErrorCode.INVALID_INPUT,
+ `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` +
+ `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` +
+ `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` +
+ `To fix this, modify the \`sizes\` attribute, or provide your own \`srcset\` value directly.`);
+ }
+ }
+}
+
/**
* Verifies that the `ngSrc` is not a Blob URL.
*/
diff --git a/packages/common/test/directives/ng_optimized_image_spec.ts b/packages/common/test/directives/ng_optimized_image_spec.ts
index 0cfb640220eaf8..ecff1024d9b42c 100644
--- a/packages/common/test/directives/ng_optimized_image_spec.ts
+++ b/packages/common/test/directives/ng_optimized_image_spec.ts
@@ -14,7 +14,7 @@ import {expect} from '@angular/platform-browser/testing/src/matchers';
import {withHead} from '@angular/private/testing';
import {createImageLoader, IMAGE_LOADER, ImageLoader, ImageLoaderConfig} from '../../src/directives/ng_optimized_image/image_loaders/image_loader';
-import {ABSOLUTE_SRCSET_DENSITY_CAP, assertValidNgSrcset, NgOptimizedImage, RECOMMENDED_SRCSET_DENSITY_CAP} from '../../src/directives/ng_optimized_image/ng_optimized_image';
+import {ABSOLUTE_SRCSET_DENSITY_CAP, assertValidNgSrcset, IMAGE_CONFIG, ImageConfig, NgOptimizedImage, RECOMMENDED_SRCSET_DENSITY_CAP} from '../../src/directives/ng_optimized_image/ng_optimized_image';
import {PRECONNECT_CHECK_BLOCKLIST} from '../../src/directives/ng_optimized_image/preconnect_link_checker';
describe('Image directive', () => {
@@ -99,11 +99,11 @@ describe('Image directive', () => {
'the `src` attribute.');
});
- it('should throw if both `ngSrc` and `srcset` is present', () => {
+ it('should throw if both `ngSrcet` and `srcset` is present', () => {
setupTestingModule();
const template =
- '';
+ '';
expect(() => {
const fixture = createTestComponent(template);
fixture.detectChanges();
@@ -901,21 +901,6 @@ describe('Image directive', () => {
};
});
- it('should NOT set `srcset` if no `ngSrcset` value', () => {
- setupTestingModule({imageLoader});
-
- const template = `
-
- `;
- const fixture = createTestComponent(template);
- fixture.detectChanges();
-
- const nativeElement = fixture.nativeElement as HTMLElement;
- const img = nativeElement.querySelector('img')!;
- expect(img.src).toBe(`${IMG_BASE_URL}/img-100.png`);
- expect(img.srcset).toBe('');
- });
-
it('should set the `srcset` using the `ngSrcset` value with width descriptors', () => {
setupTestingModule({imageLoader});
@@ -1033,6 +1018,179 @@ describe('Image directive', () => {
`${IMG_BASE_URL}/img.png?w=300 3x`);
});
});
+
+ describe('sizes attribute', () => {
+ it('should pass through the sizes attribute', () => {
+ setupTestingModule();
+
+ const template = '';
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+
+ expect(img.getAttribute('sizes'))
+ .toBe('(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw');
+ });
+
+ it('should throw if a complex `sizes` is used', () => {
+ setupTestingModule();
+
+ const template =
+ '';
+ expect(() => {
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ })
+ .toThrowError(
+ 'NG02952: The NgOptimizedImage directive has detected that `sizes` was set to a string including pixel values. ' +
+ 'For automatic `srcset` generation, `sizes` must only include responsive values, such as `sizes="50vw"` or ' +
+ '`sizes="(min-width: 768px) 50vw, 100vw"`. To fix this, modify the `sizes` attribute, or provide your own \`srcset\` value directly.');
+ });
+ it('should throw if a complex `sizes` is used with ngSrcset', () => {
+ setupTestingModule();
+
+ const template =
+ '';
+ expect(() => {
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ })
+ .toThrowError(
+ 'NG02952: The NgOptimizedImage directive has detected that `sizes` was set to a string including pixel values. ' +
+ 'For automatic `srcset` generation, `sizes` must only include responsive values, such as `sizes="50vw"` or ' +
+ '`sizes="(min-width: 768px) 50vw, 100vw"`. To fix this, modify the `sizes` attribute, or provide your own \`srcset\` value directly.');
+ });
+ it('should not throw if a complex `sizes` is used with a custom srcset', () => {
+ setupTestingModule();
+
+ const template =
+ '';
+ expect(() => {
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ }).not.toThrow();
+ });
+ });
+
+ describe('automatic srcset generation', () => {
+ const imageLoader = (config: ImageLoaderConfig) => {
+ const width = config.width ? `?w=${config.width}` : ``;
+ return `${IMG_BASE_URL}/${config.src}${width}`;
+ };
+
+ it('should add a responsive srcset to the img element if sizes attribute exists', () => {
+ setupTestingModule({imageLoader});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset'))
+ .toBe(`${IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=750 750w, ${
+ IMG_BASE_URL}/img?w=828 828w, ${IMG_BASE_URL}/img?w=1080 1080w, ${
+ IMG_BASE_URL}/img?w=1200 1200w, ${IMG_BASE_URL}/img?w=1920 1920w, ${
+ IMG_BASE_URL}/img?w=2048 2048w, ${IMG_BASE_URL}/img?w=3840 3840w`);
+ });
+
+ it('should use the long responsive srcset if sizes attribute exists and is less than 100vw',
+ () => {
+ setupTestingModule({imageLoader});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset'))
+ .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=32 32w, ${
+ IMG_BASE_URL}/img?w=48 48w, ${IMG_BASE_URL}/img?w=64 64w, ${
+ IMG_BASE_URL}/img?w=96 96w, ${IMG_BASE_URL}/img?w=128 128w, ${
+ IMG_BASE_URL}/img?w=256 256w, ${IMG_BASE_URL}/img?w=384 384w, ${
+ IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=750 750w, ${
+ IMG_BASE_URL}/img?w=828 828w, ${IMG_BASE_URL}/img?w=1080 1080w, ${
+ IMG_BASE_URL}/img?w=1200 1200w, ${IMG_BASE_URL}/img?w=1920 1920w, ${
+ IMG_BASE_URL}/img?w=2048 2048w, ${IMG_BASE_URL}/img?w=3840 3840w`);
+ });
+
+ it('should add a fixed srcset to the img element if sizes attribute does not exist', () => {
+ setupTestingModule({imageLoader});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset'))
+ .toBe(`${IMG_BASE_URL}/img?w=100 1x, ${IMG_BASE_URL}/img?w=200 2x`);
+ });
+
+ it('should use a custom breakpoint set if one is provided', () => {
+ const imageConfig = {
+ breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 1280, 3840],
+ };
+ setupTestingModule({imageLoader, imageConfig});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset'))
+ .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=32 32w, ${
+ IMG_BASE_URL}/img?w=48 48w, ${IMG_BASE_URL}/img?w=64 64w, ${
+ IMG_BASE_URL}/img?w=96 96w, ${IMG_BASE_URL}/img?w=128 128w, ${
+ IMG_BASE_URL}/img?w=256 256w, ${IMG_BASE_URL}/img?w=384 384w, ${
+ IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=1280 1280w, ${
+ IMG_BASE_URL}/img?w=3840 3840w`);
+ });
+
+ it('should sort custom breakpoint set', () => {
+ const imageConfig = {
+ breakpoints: [48, 16, 3840, 640, 1280],
+ };
+ setupTestingModule({imageLoader, imageConfig});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset'))
+ .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=48 48w, ${
+ IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=1280 1280w, ${
+ IMG_BASE_URL}/img?w=3840 3840w`);
+ });
+
+ it('should disable automatic srcset generation if "unoptimized" attribute is set', () => {
+ setupTestingModule({imageLoader});
+
+ const template = `
+
+ `;
+ const fixture = createTestComponent(template);
+ fixture.detectChanges();
+ const nativeElement = fixture.nativeElement as HTMLElement;
+ const img = nativeElement.querySelector('img')!;
+ expect(img.getAttribute('srcset')).toBeNull();
+ });
+ });
});
});
@@ -1059,8 +1217,12 @@ class TestComponent {
priority = false;
}
-function setupTestingModule(
- config?: {imageLoader?: ImageLoader, extraProviders?: Provider[], component?: Type}) {
+function setupTestingModule(config?: {
+ imageConfig?: ImageConfig,
+ imageLoader?: ImageLoader,
+ extraProviders?: Provider[],
+ component?: Type
+}) {
const defaultLoader = (config: ImageLoaderConfig) => {
const isAbsolute = /^https?:\/\//.test(config.src);
return isAbsolute ? config.src : window.location.origin + '/' + config.src;
@@ -1072,6 +1234,9 @@ function setupTestingModule(
{provide: IMAGE_LOADER, useValue: loader},
...extraProviders,
];
+ if (config?.imageConfig) {
+ providers.push({provide: IMAGE_CONFIG, useValue: config.imageConfig});
+ }
TestBed.configureTestingModule({
declarations: [config?.component ?? TestComponent],