簡體   English   中英

我怎么知道子元素何時在Angular中完成渲染?

[英]How do I know when child element has finished rendering in Angular?

我有一個布局組件,其中有一個<router-outlet> ,其中子組件由路由器動態插入。

我怎么知道,插入子元素並完成構建它的視圖?

此外,我無法手動觸發子組件中的事件,因為我希望此解決方案是通用的。

路由器調用activateWith方法在router-outlet上創建一個componentRef並將其連接到router-outlet容器。 然后它發出activate事件:

this.activateEvents.emit(this.activated.instance);

此時,組件的視圖已創建並附加到DOM。 但是,只執行附加組件的constructor 沒有生命周期鈎子。 在下一次更改檢測期間,將調用附加組件的生命周期掛鈎。

您可以通過(activate)輸出訂閱此事件,因為yurzui顯示:

<router-outlet (activate)="onActivated($event)"></router-outlet>

或使用事件發射器,不建議:

this.outlet.activateEvents.subscribe((component) => {
      this.activated = true; 
});

因此,例如,如果您想知道何時為子組件調用了ngOnInit ,您可以執行以下操作:

const activated = false;

onActivated() {
   this.activated = true; 
});

ngAfterViewInit() {
   if (this.activated) {
     // lifecycle hooks for the child component have been called
   }
}

您可以使用@ViewChild綁定綁定到<router-outlet>組件。

對於使用<router-outlet>任何組件,請添加:

/**
 * Gain access to the inner route child.
 */
@ViewChild(RouterOutlet)
public outlet: RouterOutlet;

然后你可以聽到這樣的變化:

public ngAfterViewInit(): void {
    this.outlet.activateEvents.subscribe((component) => {
         // gets passed the new child component instance
    });
    this.outlet.deactivateEvents.subscribe(() => {
         // the child component has been destroyed
    });
    if (this.outlet.isActivated) {
        // will be false if there is no child route active
    }
}

暫無
暫無

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

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