什么时候会为动态加载的角度分量触发OnInit事件?

时间:2019-06-03 12:10:09

标签: angular angular-dynamic-components

我正在用以下代码动态加载Angular组件(MyComponent)。创建完之后,我还将一些数据传递给组件。

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

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

OnInit的{​​{1}}生命周期事件何时触发?调用MyComponent之后会立即触发它吗?还是仅在createComponent()之后调用它?

2 个答案:

答案 0 :(得分:1)

来自the documentation

  

在Angular首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。

     

在第一个ngOnChanges()之后调用一次。

这意味着一旦插值完成并设置了输入,便会调用它。

答案 1 :(得分:1)

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 
相关问题