角2获取元素高度 [英] Angular 2 get element height

查看:47
本文介绍了角2获取元素高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a really simple example here

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

Its just an angular app with a single div

是否有可能获取角度为div的高度

Is it possible to get the height of the div in angular

我以为我可以使用@ViewChild和offsetHeight

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

}

推荐答案

修饰后的变量elementView仅在ngAfterViewInit生命周期挂钩之后设置:

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

请参见 https://angular.io/api/core/ViewChild#how -使用以获取更多信息.

See https://angular.io/api/core/ViewChild#how-to-use for more info.

这篇关于角2获取元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆