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 的信息。
该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。
| 归档时间: |
|
| 查看次数: |
14641 次 |
| 最近记录: |