I have an Angular directive that ouputs the height and width from the getBoundingClientRect() of whatever element the directive is placed in.
When the window size changes, the directive outputs the new size.
My issue is that on the first load of a page, the directive outputs a height which is massively too big (almost twice the height). However, one resize, the height outputted it correct.
My directive code below:
export class ElementSizeObserverDirective implements AfterViewInit, OnInit {
@Output() spaceSizeChange: EventEmitter<ScreenSize> =
new EventEmitter<ScreenSize>();
constructor(
private elRef: ElementRef,
private autoUnsubscribeDirective: AutoUnsubscribeDirective
) {}
ngOnInit(): void {
/* first get the initial screen size after init */
setTimeout(() => {
this.getScreenSize();
});
}
ngAfterViewInit(): void {
/* and then whenever the screen size changes */
fromEvent(window, 'resize')
.pipe(
/* throttleTime(50), */
takeUntil(this.autoUnsubscribeDirective.destroyNotifier$)
)
.subscribe(() => this.getScreenSize());
}
private getScreenSize(): void {
if (!this.elRef) {
return;
}
const reboundClientRec = this.elRef.nativeElement.getBoundingClientRect();
const {width, height} = reboundClientRec;
if (width !== undefined && height !== undefined) {
this.spaceSizeChange.emit({width, height});
}
}
}
On first page load, the height is almost 2 times the actual height. I am not sure where this height is coming from, and how to fix it.
My issue ended up being not related to the screen size directive at all. But rather having a large set of loading cards.