Reputation: 83
I'm trying to retrieve a component's height within itself (using ElementRef), which is located within a css grid layout. Background is the component renders images via picture-tag and depending on the grid layout the component might be rather small, but it would still render images dedicated to a large viewport. So I want to check the component's actual dimensions and dictate whatever image size I allow for this very instance.
EDIT: the thing is that the grid layout is styled in a way, that all images are cropped if necessary. So if you have a grid element that has a column like shape, the source image must stay rather big, but lots of its content left and right will be cut off. I'm trying to target the grid elements that still retain the same proportions of the image. this is where I need to restrict large srcsets from being rendered.
The Problem is that even for the Lifecycle Hook "AfterViewInit" I still get height values of "0" for "this.elRef.nativeElement.offsetHeight". (btw. For some reason the offsetWidth is returned properly in time, but not the height.) Only "AfterViewChecked" would finally give me the final height that I can work with, but that lifecycle hook is called countless times, which would lead to all the repeated iterations of the same logic building the component. This what I tried and probably would work, but is no option due to the repeated iterations.
class ImageComponent implements AfterViewChecked {
heightSubject = new BehaviorSubject(0);
public height$: Observable<number> = this.heightSubject.asObservable();
constructor(public component: CmsComponentData<CmsComponent>, elRef: ElementRef){}
ngAfterViewChecked(): void {
this.heightSubject.next(this.elRef.nativeElement.offsetHeight);
}
compData$: Observable<BannerData> = combineLatest([this.component.data$, this.height$]).pipe(
map(([data, height] : [CmsBannerComponent, number]) => {
if(height < 500){
return data.smallImage;
}
return data.bigImage;
});
}
Is there a proper way to reliably get a component's dimensions in such cases?
Best Regards
Upvotes: 0
Views: 54