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

Sar*_*non 7 angular angular-dynamic-components

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

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

(<MyComponent>componentRef.instance).setData(data);
Run Code Online (Sandbox Code Playgroud)

什么时候会触发OnInit生命周期事件MyComponent?调用后会立即触发createComponent()吗?或者它只会在之后被调用setData()

yur*_*zui 17

ngOnInithook 将在下一个涵盖动态组件的更改检测周期中触发。通过覆盖,我的意思是应该创建动态组件的视图,并将其附加到 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
Run Code Online (Sandbox Code Playgroud)

另一方面,在您的情况下,ngOnInit 将可以访问您在 setData 调用期间传入的任何属性。

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

componentRef.instance.x = 3;

// somewhen later ngOnInit will be called 
Run Code Online (Sandbox Code Playgroud)