什么时候会为动态加载的角度分量触发OnInit事件? [英] When is OnInit event triggered for a dynamically loaded angular component?

查看:57
本文介绍了什么时候会为动态加载的角度分量触发OnInit事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am dynamically loading an Angular component (MyComponent) with the following code. 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);

何时会触发 MyComponent OnInit 生命周期事件?调用 createComponent()后会立即触发它吗?还是只在 setData()之后调用它?

When will the OnInit lifecycle event of the MyComponent be triggered? Will it be triggered immediately after calling createComponent()? Or will it only be called after setData()?

推荐答案

ngOnInit 挂钩将在涉及动态组件的下一个更改检测周期中触发.通过覆盖,我的意思是应该创建动态组件的视图,并将其附加到Angular变化检测树.

ngOnInit hook will be triggered on the next change detection cycle that covers dynamic component. By covering I mean that the view for dynamic component should be created and it should be attached to Angular change detection tree.

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

ViewContainerRef::createComponent method only attaches newly created View to the current view and renders it.

新视图连接到树后,Angular可以在更改检测阶段对其进行检查.

Once that new View is attached to the tree Angular can check it during change detection phase.

一旦NgZone确定没有计划的微任务,下一个变化检测阶段便开始.例如,它会在事件处理程序之后或http调用之后发生.

The next change detection phase starts once NgZone determines that there is no microtasks scheduled. For example, it will happen after your event handler or after http call.

您可以为创建的视图手动触发更改检测:

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

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

On the other hand, in your case ngOnInit will have access to any properties you passed in during setData call.

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

componentRef.instance.x = 3;

// somewhen later ngOnInit will be called 

这篇关于什么时候会为动态加载的角度分量触发OnInit事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆