[英]How to make a JS function wait for the component to be loaded in angular
我想在加載后在 angular 中獲取組件的寬度,但它返回 0 因為尚未加載 div,即使我在 AfterViewInit 中編寫代碼也是如此。 使其在開發中工作的唯一解決方案是將超時設置為 100 毫秒。 有沒有更清潔和更好的方法呢?
<div id='test'></div>
#test {
width: 200px;
height: 300px;
background: green;
}
ngAfterViewInit(): void {
setTimeout(function (){
console.log(document.getElementById('test').clientWidth);
}, 100)
}
您可以在ngAfterViewChecked()
生命周期掛鈎而不是ngAfterViewInit()
中編寫setTimeout
。
此外,您也可以使用viewChild()
指令以更清晰的方式解決您的問題。 它也不需要setTimeout
。
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;
contentWidth: number;
constructor() {
}
ngAfterViewInit() {
this.contentWidth= this.elementView.nativeElement.offsetWidth;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.