簡體   English   中英

Angular 2組件完全加載后

[英]When an Angular 2 component has fully loaded

我似乎找不到一個鈎子,通過它我可以知道由其他子組件組成的組件已完全完成加載,包括數據綁定和所有操作。 例如,為ParentComponent使用以下模板:

<div>
    <child-one>
        {{textOne}}
    </child-one>
    <child-two>
        {{textTwo}}
    </child-two>
</div>

任何建議都將受到高度贊賞。

這是不對的! 初始化視圖時會觸發ngAfterViewInit。在其中插入一個斷點,您將看到。 Angular 2確實缺少了解視圖實際何時完全加載的鈎子! 但是,作為一種解決方法,您可以嘗試執行以下操作:

ngAfterViewInit() {
    console.log('View is being initialized');
    console.log(this.el.nativeElement.offsetHeight);

    setTimeout(() => {
        console.log('View is fully loaded');
        console.log(this.el.nativeElement.offsetHeight);
    }, 0);
}

ngAfterViewInit() {}或傳遞內容( <ng-content> )時,將在ngAfterContentInit()之后。

基於Dimitri的答案,我發現即使在調用ngAfterViewInit之后,某些元素仍然沒有完全加載,就我而言,我是在元素的scrollHeight之后。

使用Ionic的platform.ready()和一些超時測試,我發現內容在大約60ms之后最終被實例化,因此我將其增加到250ms,只是提供了一些擺動空間。 確實不是很理想,但這是執行檢查的最后一個生命周期鈎子……但是也許會對某人有所幫助?

constructor(public platform: Platform) {}

ngAfterViewInit() {
    this.platform.ready().then(() => {
        /* still returns 0 here */
        console.log(this.el.nativeElement.scrollHeight);

        setTimeout(() => {
            /* returns x here */
            console.log(this.el.nativeElement.scrollHeight);
        }, 250);
    });
}

我知道並不是每個人都會使用Ionic來提供Platform類,這只與我的用例有關,因為我正在使用離子圖標。 但是我留了下來,以防其他離子用戶幫忙。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM