我正在尝试根据元素的宽度和高度进行一些计算,但是由于某些原因,这些计算不能立即在AfterViewInit
生命周期钩子(Hook)上使用(均为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>
最佳答案
有必要使用ngAfterViewChecked
生命周期钩子(Hook)
,而不是ngAfterViewInit
。
正如Angular的文档所说的关于ngAfterViewChecked()
:
关于javascript - 为什么ViewChild ElementRef在ngAfterViewInit中的宽度和高度为0?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55563149/