fix(common): Warn on fill ngOptimizedImage without height (#48036)

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
This commit is contained in:
Alex Castle
2022-11-11 12:25:50 -08:00
committed by Jessica Janiuk
parent 954f700ab4
commit 8b39c38940
@@ -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
@@ -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.