How to get Dom's height in angular2?

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.


Try the function ngAfterViewInit

ngAfterViewInit(){
     console.log(document.getElementById("OuterSvg").offsetHeight);
}

And is your div HTML like it is? Otherwise you might consider removing the space after id:

<div style="width:100%;height:100%;position:relative;background-color:white" id="OuterSvg">

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>

Tags:

Angular

Ionic2