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 }
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.
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.
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.
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