typescript - Angular 2 obtener la altura del elemento
Tengo un ejemplo realmente sencillo aquí
Es solo una aplicación Angular con un único div
¿Es posible obtener la altura del div en Angular?
Pensé que podría hacerlo con @ViewChild y 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
}
Respuesta #1
La variable ViewChild decorada elementView solo se establece después del hook de ciclo de vida ngAfterViewInit:
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;
}
}
Consulta https://angular.io/api/core/ViewChild#how-to-use para más información.
Respuesta #2
Depende de lo que entiendas por "altura"
ClientHeight
devuelve la altura interior de un elemento en píxeles, incluyendo el relleno pero no la altura de la barra de desplazamiento horizontal, el borde ni el margen
Podrías usar el método Element.getBoundingClientRect() después de convertir el NativeElement a HTMLElement.
ngAfterViewInit() {
let height = (<HTMLElement>this.elementView.nativeElement).getBoundingClientRect().height
}
OffsetHeight
es una medida que incluye los bordes del elemento, el relleno vertical del elemento, la barra de desplazamiento horizontal del elemento (si está presente, si se representa) y la altura CSS del elemento. enlace
ngAfterViewInit() {
let height = this.elementView.nativeElement.offsetHeight
}
asegúrate de hacer esto después de que se haya establecido el tamaño del elemento (ngAfterViewInit()). Puedes encontrar más información sobre los Hooks del ciclo de vida de Angular aquí.
