【发布时间】:2019-04-07 20:01:41
【问题描述】:
我正在尝试根据元素的宽度和高度进行一些计算,但由于某种原因,这些在 AfterViewInit 生命周期挂钩上无法立即使用(两者均为 0)。
虽然setTimeout 似乎确实可以解决问题,但我不喜欢它。
这是什么原因造成的? 有没有更优雅的解决方案?
@ViewChild('main') mainDiv: ElementRef;
ngAfterViewInit() {
this.printMainHeight() // 0
// with setTimeout width is correctly retrieved ...
setTimeout(() => this.printMainHeight()) // 430
}
printMainHeight() {
console.log(this.mainDiv.nativeElement.getBoundingClientRect().height)
}
HTML
<div class"main" #main>
<app-toolbar></app-toolbar>
<app-list></app-list>
</div>
【问题讨论】:
-
我的第一个想法是,想想事情发生的速度有多快,一开始你有一个渲染的 dom,但它有样式吗?高度是多少?
标签: javascript html angular