Skip to content

Commit

Permalink
fix(common): Warn on fill ngOptimizedImage without height (#48036)
Browse files Browse the repository at this point in the history
Add a warning if a fill-mode image is rendered without height. This is a common occurence if the user doesn't properly set the 'position' attribute of the parent element.

PR Close #48036
  • Loading branch information
atcastle authored and thePunderWoman committed Nov 14, 2022
1 parent 629ebad commit 945432e
Showing 1 changed file with 21 additions and 0 deletions.
Expand Up @@ -365,6 +365,7 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
assertNotBlobUrl(this);
if (this.fill) {
assertEmptyWidthAndHeight(this);
assertNonZeroRenderedHeight(this, this.imgElement, this.renderer);
} else {
assertNonEmptyWidthAndHeight(this);
// Only check for distorted images when not in fill mode, where
Expand Down Expand Up @@ -862,6 +863,26 @@ function assertEmptyWidthAndHeight(dir: NgOptimizedImage) {
}
}

/**
* Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides
* guidance that this can be caused by the containing element's CSS position property.
*/
function assertNonZeroRenderedHeight(
dir: NgOptimizedImage, img: HTMLImageElement, renderer: Renderer2) {
const removeListenerFn = renderer.listen(img, 'load', () => {
removeListenerFn();
const renderedHeight = parseFloat(img.clientHeight as any);
if (dir.fill && renderedHeight === 0) {
console.warn(formatRuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` +
`This is likely because the containing element does not have the CSS 'position' ` +
`property set to one of the following: "relative", "fixed", or "absolute". Make this ` +
`change to ensure that the image is visible.`));
}
});
}

/**
* Verifies that the `loading` attribute is set to a valid input &
* is not used on priority images.
Expand Down

0 comments on commit 945432e

Please sign in to comment.