Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 get element height

Tags:

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  } 
like image 226
ttmt Avatar asked Apr 24 '18 10:04

ttmt


People also ask

How can I get div height in TypeScript?

Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element. This property can be used to find the height of the <div> element.

How do I use ElementRef?

To manipulate the DOM using the ElementRef , we need to get the reference to the DOM element in the component/directive. Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.


1 Answers

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.

like image 80
Kelvin Lai Avatar answered Sep 22 '22 15:09

Kelvin Lai