角2获取元素高度

ttm*_*tmt 6 typescript angular

我这里有一个非常简单的例子

它只是一个带有单个div的有角度的应用程序

是否有可能以角度获得div的高度

我以为我可以用@ViewChild和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

}
Run Code Online (Sandbox Code Playgroud)

Jag*_*rJo 14

取决于你所说的“高度”是什么意思

客户端高度

以像素为单位返回元素的内部高度,包括填充但不包括水平滚动条的高度、边框或边距

您可以在将NativeElement 转换HTMLElement后使用Element.getBoundingClientRect()方法。

ngAfterViewInit() {
    let height = (<HTMLElement>this.elementView.nativeElement).getBoundingClientRect().height
}
Run Code Online (Sandbox Code Playgroud)

偏移高度

是一个度量,包括元素边框、元素垂直填充、元素水平滚动条(如果存在,如果呈现)和元素 CSS 高度。关联

ngAfterViewInit() {
    let height = this.elementView.nativeElement.offsetHeight
}
Run Code Online (Sandbox Code Playgroud)

确保在设置元素大小后执行此操作(ngAfterViewInit())。你可以在这里找到更多关于Angular Lifecycle Hooks 的信息

  • 如果稍后调整显示屏大小,结果会如何? (3认同)

Kel*_*Lai 5

ViewChild装饰变量elementView仅是后置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;
  }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见https://angular.io/api/core/ViewChild#how-to-use