I have an issue with getting dynamically height of PageSlotComponent (for example 'TopHeaderSlot') or a Component.
I have tried it using ViewChilder or using ViewChild, but component has *ngIf's inside.
@ViewChildren('topHeader') public topHeader?: QueryList<ElementRef>;
Even through I see a value offsetHeight when trying it to print it returns '0'. Reason behind this is becouse DOM was not ready yet so result is zero.
ngAfterViewInit(): void {
if (this.topHeader) {
console.log(this.topHeader) // prints ElementRef with a value
console.log(this.topHeader.first)
console.log(this.topHeader.first.nativeElement.offsetHeight) // doesnt return a value
}
}
How to get height of a Component or Slot?
CodePudding user response:
Your answer will depend on where and when you want this height to be used.
After your component is mounted, you get the height of the initial rendering. So, if your component is hidden with a *ngIf
, you can't have it. Otherwise, you should have the value.
You'll have to play with the where/when condition to get the height at all times, so I suggest you create a getter that does this for you :
get compHeight() {
return this.topHeader?.first?.nativeElement?.offsetHeight ?? -1;
}
If you get -1, then your component is not displayed.
Apart from that, know that the when the console displays non-primitive elements, the display is deferred : the object is evaluated at the moment you expand the object, NOT the moment you call the console.log. So you can see an element (or not see it) even though the original console show it as the opposite.