<div style="width:100%;height:100%;position:relative;background-color:white" id ="OuterSvg"> </div>
onPageLoaded(){
console.log(document.getElementById("OuterSvg").offsetHeight); //get 0.
}
ngAfterViewInit(){
console.log(document.getElementById("OuterSvg").offsetHeight); //get 0.
}
I have also tried onPageLoaded()
and ngAfterViewInit()
, but they do not work.
How to get the element's height/width after it is rendered?
Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.
outerHeight() It returns the current height of the element including the padding, border and margin optionally.
var height = document. getElementById('content'). clientHeight; That will not include any borders or scrollbars in the element, just padding.
What you want is the height of an element after Angular has processed the event lifecycles, compiled the html and injected it on the page, and the browser finished rendering that html.
You need the height only when its stable, not before. The problem is that all that is done after Angular relinquishes the Javascript VM turn, and there is no "browser finished rendering" or "layout calculated" event.
You need to give the browser a chance to calculate the height and apply it. For example call setTimeout
. This will give the browser the chance to calculate the height.
Probably an interval of zero ms would work. This is because calls to offsetHeight trigger a layout recalculation if needed (see here).
This is a general problem and is not framework specific, its just the way browsers work. In general its better to try to avoid as much as possible this kind of logic (wait until height is stable to do X), it tends to create hard to fix issues.
The event AfterViewChecked
with ngIf
worked for me. The event AfterViewChecked
event is triggered every time the DOM is updated. In addition, it is possible to send height to a child component.
As Angular documentation says:
Respond after Angular checks the component's views and child views / the view that a directive is in.
Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked()
So code looks like this:
export class YourComponent implements AfterViewChecked {
@ViewChild('fooWrapper') sidebarElementRef: ElementRef;
ngAfterViewChecked() {
this.divHeight = this.sidebarElementRef.nativeElement.offsetHeight;
}
}
HTML:
<div #fooWrapper>
<fooComponent
*ngIf="divHeight > 0"
[Height]="divHeight">
</fooComponent>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With