Skip to content

Commit d71dfe9

Browse files
karaPawel Kozlowski
authored andcommitted
fix(common): set bound width and height onto host element (angular#47082)
This commit fixes a bug in NgOptimizedImage where if you bound the width or height attribute (e.g. `[width]=width`), the attribute would only be reflected as "ng-reflect-x". The actual "width" or "height" attribute would not be set on the host element. This is a problem because the exact named attribute must be set on the element for the browser to detect it and use it to reserve space for the image (and thus prevent CLS). PR Close angular#47082
1 parent 45cc85f commit d71dfe9

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,11 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
267267
observer.registerImage(this.getRewrittenSrc(), this.rawSrc));
268268
}
269269
}
270+
// Must set width/height explicitly in case they are bound (in which case they will
271+
// only be reflected and not found by the browser)
272+
this.setHostAttribute('width', this.width!.toString());
273+
this.setHostAttribute('height', this.height!.toString());
274+
270275
this.setHostAttribute('loading', this.getLoadingBehavior());
271276
this.setHostAttribute('fetchpriority', this.getFetchPriority());
272277
// The `src` and `srcset` attributes should be set last since other attributes

packages/common/test/directives/ng_optimized_image_spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@ describe('Image directive', () => {
6868
expect(_fetchpriorityAttrId).toBeLessThan(_srcAttrId); // was set after `src`
6969
});
7070

71+
it('should always reflect the width/height attributes if bound', () => {
72+
setupTestingModule();
73+
74+
const template = '<img rawSrc="path/img.png" [width]="width" [height]="height">';
75+
const fixture = createTestComponent(template);
76+
fixture.detectChanges();
77+
78+
const nativeElement = fixture.nativeElement as HTMLElement;
79+
const img = nativeElement.querySelector('img')!;
80+
expect(img.getAttribute('width')).toBe('100');
81+
expect(img.getAttribute('height')).toBe('50');
82+
});
83+
7184
describe('setup error handling', () => {
7285
it('should throw if both `src` and `rawSrc` are present', () => {
7386
setupTestingModule();

0 commit comments

Comments
 (0)