Getting element height Getting element height angular angular

Getting element height


The correct way is to use @ViewChild() decorator:

https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

Template:

<div class="view-main-screen" #mainScreen></div>

Component:

import { ElementRef, ViewChild } from '@angular/core';export class viewApp{      @ViewChild('mainScreen') elementView: ElementRef;      viewHeight: number;      constructor() {      }      clickMe(){        this.viewHeight = this.elementView.nativeElement.offsetHeight;      }}

That should do it but obviously you need to add your Component decorator.

Edit:

For Angular 8 or later you need to provide the 2nd parameter in ViewChild

@ViewChild('mainScreen', {read: ElementRef, static:false}) elementView: ElementRef;


update2

constructor(private elementRef:ElementRef) {}someMethod() {   console.log(this.elementRef.nativeElement.offsetHeight);}

Accessing nativeElement directly is discouraged but current Angular doesn't provide other ways as far as I know.

update

https://github.com/angular/angular/pull/8452#issuecomment-220460761

mhevery commented 12 days ago We have decided to remove Ruler service, and so it is not part of the public API.

original

As far as I know the Ruler class should provide that functionalityhttps://github.com/angular/angular/blob/master/modules/angular2/src/platform/browser/ruler.ts if this isn't enought you probably need to access elementRef.nativeElement and use direct DOM access and functions provided by the elements.

new Ruler(DOM).measure(this.elRef).then((rect: any) => {});

Rules service is safe in WebWorker. See also the comments on https://github.com/angular/angular/issues/6515#issuecomment-173353649


<div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>itemClick(dom){  var height=dom.clientHeight;  // ...}