什么时候为动态加载的 angular 组件触发 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()之后调用?

来自 the documentation :

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

Called once, after the first ngOnChanges().

这意味着在插值完成并设置输入后调用它。

ngOnInit 钩子将在下一个覆盖动态组件的变化检测周期被触发。通过覆盖我的意思是应该创建动态组件的视图并且它应该附加到 Angular 变化检测树。

ViewContainerRef::createComponent 方法仅将新创建的视图附加到当前视图并呈现它。

一旦新视图附加到树 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