Angular 2获取元素高度

30

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

它只是一个带有单个

的angular应用程序

是否有可能在angular中获取

的高度

我认为我可以使用@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

}
2个回答

35

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

请查看https://angular.io/api/core/ViewChild#how-to-use获取更多信息。


1
如果是静态查询,我们也可以在ngOnInit钩子中获取ViewChild。 - yurzui
1
@yurzui 很有趣!但我不明白?我以为 ngOnInit 并没有完全绘制所有 DOM,只有 ngAfterViewInit 是可靠的?你是如何定义“静态查询”的?如果我用我的类更改 DOM,那么正确的值只会在 ngAfterViewInit 中出现?我怎么知道我处于一个可以从 ngOnInit 的早期受益的情况下? - tatsu
我遇到了这个错误,该如何修复?ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '800'。 - user15293929

22

根据你对“height”的理解不同而定。

客户端高度

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

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

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

OffsetHeight

OffsetHeight是一个包括元素边框、元素垂直内边距、元素水平滚动条(如果存在且被渲染)、以及元素CSS高度的测量值。链接

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

在元素的大小设置后 (ngAfterViewInit()),确保执行此操作。您可以在此处了解有关Angular生命周期钩子的更多信息。


3
如果显示器稍后被调整大小,那会怎么样呢? - Mawg says reinstate Monica
谢谢您对ngAfterViewInit()的评论。 - Steve Giles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接