[英]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);
什么時候會觸發MyComponent
的OnInit
生命周期事件? 調用createComponent()
后會立即觸發它嗎? 還是僅在setData()
之后調用它?
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.