簡體   English   中英

什么時候會為動態加載的角度分量觸發OnInit事件?

[英]When is OnInit event triggered for a dynamically loaded angular component?

我正在使用以下代碼動態加載Angular組件( MyComponent )。 創建后,我還將一些數據傳遞給該組件。

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
this.viewContainerRef.clear();
let componentRef = this.viewContainerRef.createComponent(componentFactory);

(<MyComponent>componentRef.instance).setData(data);

什么時候會觸發MyComponentOnInit生命周期事件? 調用createComponent()后會立即觸發它嗎? 還是僅在setData()之后調用它?

文檔中

在Angular首先顯示數據綁定屬性並設置指令/組件的輸入屬性后,初始化指令/組件。

在第一個ngOnChanges()之后調用一次。

這意味着在完成插值並設置輸入后即會調用它。

ngOnInit掛鈎將在涉及動態組件的下一個更改檢測周期中觸發。 通過覆蓋,我的意思是應該創建動態組件的視圖並將其附加到Angular變化檢測樹。

ViewContainerRef::createComponent方法僅將新創建的View附加到當前視圖並進行呈現。

一旦新視圖附加到樹上,Angular就可以在更改檢測階段對其進行檢查。

一旦NgZone確定沒有計划的微任務,下一個更改檢測階段便開始。 例如,它將在事件處理程序之后或http調用之后發生。

您可以為創建的視圖手動觸發更改檢測:

const componentRef = this.target.createComponent(componentFactory);

componentRef.changeDetectorRef.detectChanges(); // ngOnInit will be called 

componentRef.instance.x = 3; // access this.x in ngOnInit will give you undefined

另一方面,在您的情況下,ngOnInit將有權訪問在setData調用期間傳遞的任何屬性。

const componentRef = this.target.createComponent(componentFactory);

componentRef.instance.x = 3;

// somewhen later ngOnInit will be called 

暫無
暫無

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

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