简体   繁体   English

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

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

I am dynamically loading an Angular component ( MyComponent ) with the following code. 我正在使用以下代码动态加载Angular组件( MyComponent )。 I am also passing some data to the component after creating it. 创建后,我还将一些数据传递给该组件。

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

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

When will the OnInit lifecycle event of the MyComponent be triggered? 什么时候会触发MyComponentOnInit生命周期事件? Will it be triggered immediately after calling createComponent() ? 调用createComponent()后会立即触发它吗? Or will it only be called after setData() ? 还是仅在setData()之后调用它?

From the documentation : 文档中

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. 在Angular首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。

Called once, after the first ngOnChanges(). 在第一个ngOnChanges()之后调用一次。

This means it's called once the interpolation is done and the inputs are set. 这意味着在完成插值并设置输入后即会调用它。

ngOnInit hook will be triggered on the next change detection cycle that covers dynamic component. ngOnInit挂钩将在涉及动态组件的下一个更改检测周期中触发。 By covering I mean that the view for dynamic component should be created and it should be attached to Angular change detection tree. 通过覆盖,我的意思是应该创建动态组件的视图并将其附加到Angular变化检测树。

ViewContainerRef::createComponent method only attaches newly created View to the current view and renders it. ViewContainerRef::createComponent方法仅将新创建的View附加到当前视图并进行呈现。

Once that new View is attached to the tree Angular can check it during change detection phase. 一旦新视图附加到树上,Angular就可以在更改检测阶段对其进行检查。

The next change detection phase starts once NgZone determines that there is no microtasks scheduled. 一旦NgZone确定没有计划的微任务,下一个更改检测阶段便开始。 For example, it will happen after your event handler or after http call. 例如,它将在事件处理程序之后或http调用之后发生。

You can manually trigger change detection for that created view: 您可以为创建的视图手动触发更改检测:

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

On the other hand, in your case ngOnInit will have access to any properties you passed in during setData call. 另一方面,在您的情况下,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