获取元素高度 [英] Getting element height
问题描述
我很好奇我是否可以从组件模板获取元素属性. 所以我在课堂上做了一个简单的div,并且我做了这个课:
I was curious if I can get element properties form component template. So I have made simple div with class and I've made this class:
export class viewApp{
elementView: any;
viewHeight: number;
myDOM: Object;
constructor() {
this.myDOM = new BrowserDomAdapter();
}
clickMe(){
this.elementView = this.myDOM.query('div.view-main-screen');
this.viewHeight = this.myDOM.getStyle(this.elementView, 'height');
}
}
getStyle()
,query()
来自 BrowserDomAdapter .
我的问题是,当我尝试获取高度时,它是null
,但是当我通过setStyle()
设置某个高度,然后又通过getStyle()
得到它时,它返回正确的值.
在浏览器中检查DOM和样式后,我发现这是由于两个CSS元素引起的.一个是.view-main-screen[_ngcontent-aer-1]{}
,第二个是element{}
.
.view-main-screen
具有某些样式,但是element为空.当我按setStyle()
添加样式时,它会出现在element{}
中.这是为什么?如何使用Angular2获取元素属性?
getStyle()
, query()
are from BrowserDomAdapter.
My problem is when I try to get height it is null
, but when I set some height by setStyle()
and then I get it by getStyle()
it returns proper value.
After checking DOM and styles in browser I discovered that is because of two CSS elements. One is: .view-main-screen[_ngcontent-aer-1]{}
and second one is element{}
.
.view-main-screen
has some stylings, but element is empty. When I add styles by setStyle()
it appears in element{}
. Why is that? How can I get element properties by using Angular2?
推荐答案
正确的方法是使用@ViewChild()
装饰器:
The correct way is to use @ViewChild()
decorator:
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
模板:
<div class="view-main-screen" #mainScreen></div>
组件:
import { ElementRef, ViewChild } from '@angular/core';
export class viewApp{
@ViewChild('mainScreen') elementView: ElementRef;
viewHeight: number;
constructor() {
}
clickMe(){
this.viewHeight = this.elementView.nativeElement.offsetHeight;
}
}
应该这样做,但是显然您需要添加组件装饰器.
That should do it but obviously you need to add your Component decorator.
对于Angular 8或更高版本,您需要在ViewChild中提供第二个参数
For Angular 8 or later you need to provide the 2nd parameter in ViewChild
@ViewChild('mainScreen', {read: ElementRef, static:false}) elementView: ElementRef;
这篇关于获取元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!