ttmt
ttmt

Reputation: 4986

Angular 2 get element height

I have a really simple example here

Its just an angular app with a single div

Is it possible to get the height of the div in angular

I thought I could do it with @ViewChild and offsetHeight

import {Component, ElementRef, ViewChild} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html'
})

export class AppComponent{

  @ViewChild('content') elementView: ElementRef;

  contentHeight: number;

  constructor() {

  }

  //contentHeight = this.elementView.nativeElement.offsetHeight

}

Upvotes: 32

Views: 90397

Answers (2)

JaggerJo
JaggerJo

Reputation: 934

Depends on what you mean by "height"

ClientHeight

returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin

You could use the Element.getBoundingClientRect() method after casting the NativeElement to HTMLElement.

ngAfterViewInit() {
    let height = (<HTMLElement>this.elementView.nativeElement).getBoundingClientRect().height
}

OffsetHeight

is a measurement which includes the element borders, the element vertical padding, the element horizontal scrollbar (if present, if rendered) and the element CSS height. link

ngAfterViewInit() {
    let height = this.elementView.nativeElement.offsetHeight
}

make sure yo do this after the size of the element was set (ngAfterViewInit()). You can find more aboute Angular Lifecycle Hooks here .

Upvotes: 23

Kelvin Lai
Kelvin Lai

Reputation: 2279

The ViewChild decorated variable elementView is only set after the ngAfterViewInit life cycle hook:

import {Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html'
})

export class AppComponent implements AfterViewInit {

  @ViewChild('content') elementView: ElementRef;

  contentHeight: number;

  constructor() {

  }

  ngAfterViewInit() {
      this.contentHeight = this.elementView.nativeElement.offsetHeight;
  }
}

See https://angular.io/api/core/ViewChild#how-to-use for more info.

Upvotes: 36

Related Questions