Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[draft] Add 'fill mode' to NgOptimizedImage #47727

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions aio/content/guide/image-directive.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ providers: [

</code-example>

### Using `fill` mode

In cases where you want to have an image fill a containing element, you can use the `fill` attribute. This is often useful when you want to achieve a "background image" behavior, or when you don't know the exact width and height of your image.

When you add the `fill` attribute to your image, you do not need and should not include a `width` and `height`, as in this example:

<code-example format="typescript" language="typescript">

&lt;img ngSrc="cat.jpg" fill&gt;

</code-example>

### Adjusting image styling

Depending on the image's styling, adding `width` and `height` attributes may cause the image to render differently. `NgOptimizedImage` warns you if your image styling renders the image at a distorted aspect ratio.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
*/
@Input() sizes?: string;

/**
* The base `sizes` attribute passed through to the `<img>` element.
* Providing sizes causes the image to create an automatic responsive srcset.
*/
@Input() style?: string;

/**
* The intrinsic width of the image in pixels.
*/
Expand Down Expand Up @@ -326,6 +332,19 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
}
private _disableOptimizedSrcset = false;

/**
* Sets the image to "fill mode," which eliminates the height/width requirement and adds
* styles such that the image fills its containing element.
*/
@Input()
set fill(value: string|boolean|undefined) {
this._fill = inputToBoolean(value);
}
get fill(): boolean {
return this._fill;
}
private _fill = false;

/**
* Value of the `src` attribute if set on the host `<img>` element.
* This input is exclusively read to assert that `src` is not set in conflict
Expand All @@ -352,7 +371,11 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
}
assertNotBase64Image(this);
assertNotBlobUrl(this);
assertNonEmptyWidthAndHeight(this);
if (this.fill) {
assertEmptyWidthAndHeight(this);
} else {
assertNonEmptyWidthAndHeight(this);
}
assertValidLoadingInput(this);
assertNoImageDistortion(this, this.imgElement, this.renderer);
if (!this.ngSrcset) {
Expand All @@ -379,8 +402,15 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
private setHostAttributes() {
// Must set width/height explicitly in case they are bound (in which case they will
// only be reflected and not found by the browser)
this.setHostAttribute('width', this.width!.toString());
this.setHostAttribute('height', this.height!.toString());
if (this.fill) {
this.setHostAttribute('style', this.getFillStyle())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd be great to avoid custom parsing of styles and writing them directly to the DOM via renderer.

The "style" attribute values are handled by the framework and it takes into account various use-cases which might be broken because of writing to the DOM directly.

Instead, we can try to lean on the framework functionality and set extra styles via host binding, similar to this example:

https://github.com/angular/components/blob/f9583184d6ca487970ee70a1c05cec6e36f3e18c/src/material/legacy-progress-spinner/progress-spinner.ts#L100-L101

This would delegate the styling processing, overrides and handing of the "style" attribute bindings to the framework. WDYT?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I think this is actually a necessity, otherwise this call would clobber user-applied style bindings).

} else {
this.setHostAttribute('width', this.width!.toString());
this.setHostAttribute('height', this.height!.toString());
if (this.style) {
this.setHostAttribute('style', this.style)
}
}

this.setHostAttribute('loading', this.getLoadingBehavior());
this.setHostAttribute('fetchpriority', this.getFetchPriority());
Expand All @@ -397,6 +427,27 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
}
}

private getFillStyle(): string {
const fillStyle = {
position: 'absolute',
width: '100%',
height: '100%',
left: '0',
top: '0',
right: '0',
bottom: '0'
} let providedStyles: {[key: string]: string|number} = {} if (this.style) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like some semicolons are missing, thus the formatting is broken.

this.style.split(';').forEach(styleKVP => {
const [key, value] = styleKVP.split(':')
if (key && value) {
providedStyles[key.trim()] = value.trim();
}
})
}
const combinedStyles = Object.assign(providedStyles, fillStyle);
return Object.entries(combinedStyles).map(kvp => `${kvp[0]}: ${kvp[1]}`).join('; ');
}

ngOnChanges(changes: SimpleChanges) {
if (ngDevMode) {
assertNoPostInitInputChange(
Expand Down Expand Up @@ -787,6 +838,22 @@ function assertNonEmptyWidthAndHeight(dir: NgOptimizedImage) {
}
}

/**
* Verifies that width and height are not set. Used in fill mode, where those attributes don't make
* sense.
*/
function assertEmptyWidthAndHeight(dir: NgOptimizedImage) {
if (dir.width || dir.height) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${
imgDirectiveDetails(
dir.ngSrc)} the attributes \`height\` and/or \`width\` are present ` +
`along with the \`fill\` attribute. Because \`fill\` mode causes an image to fill its containing ` +
`element, the size attributes have no effect and should be removed.`);
}
}

/**
* Verifies that the `loading` attribute is set to a valid input &
* is not used on priority images.
Expand Down
52 changes: 52 additions & 0 deletions packages/common/test/directives/ng_optimized_image_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1192,6 +1192,58 @@ describe('Image directive', () => {
expect(img.getAttribute('srcset')).toBeNull();
});
});
describe('fill mode', () => {
it('should allow unsized images in fill mode', () => {
setupTestingModule();

const template = '<img ngSrc="path/img.png" fill>';
expect(() => {
const fixture = createTestComponent(template);
fixture.detectChanges();
}).not.toThrow();
});
it('should throw if width is provided for fill mode image', () => {
setupTestingModule();

const template = '<img ngSrc="path/img.png" width="500" fill>';
expect(() => {
const fixture = createTestComponent(template);
fixture.detectChanges();
})
.toThrowError(
'NG02952: The NgOptimizedImage directive (activated on an <img> element with the ' +
'`ngSrc="path/img.png"`) has detected that the attributes `height` and/or `width` ' +
'are present along with the `fill` attribute. Because `fill` mode causes an image ' +
'to fill its containing element, the size attributes have no effect and should be removed.');
});
it('should apply appropriate styles in fill mode', () => {
setupTestingModule();

const template = '<img ngSrc="path/img.png" fill>';

const fixture = createTestComponent(template);
fixture.detectChanges();
const nativeElement = fixture.nativeElement as HTMLElement;
const img = nativeElement.querySelector('img')!;
expect(img.getAttribute('style'))
.toBe(
'position: absolute; width: 100%; height: 100%; left: 0; top: 0; right: 0; bottom: 0')
});
it('should augment existing styles in fill mode', () => {
setupTestingModule();

const template =
'<img ngSrc="path/img.png" style="border-radius: 5px; padding: 10px" fill>';

const fixture = createTestComponent(template);
fixture.detectChanges();
const nativeElement = fixture.nativeElement as HTMLElement;
const img = nativeElement.querySelector('img')!;
expect(img.getAttribute('style'))
.toBe(
'border-radius: 5px; padding: 10px; position: absolute; width: 100%; height: 100%; left: 0; top: 0; right: 0; bottom: 0')
});
});
});
});

Expand Down