Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);

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()?

like image 673
Sarath S Menon Avatar asked Jun 03 '19 12:06

Sarath S Menon


People also ask

What is Oninit in Angular?

OnInitlinkA lifecycle hook that is called after Angular has initialized all data-bound properties of a directive.

How many times ngOnInit is called?

Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). This can lead to follow up errors that hide the original error.

Which service allows us to dynamically load a component in a certain position on the page?

Angular - Dynamic component loader.

What is dynamic component in Angular?

What dynamic components are. Dynamic means, that the components location in the application is not defined at buildtime. That means, that it is not used in any angular template. Instead, the component is instantiated and placed in the application at runtime.


1 Answers

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 method only attaches newly created View to the current view and renders it.

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

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

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 
like image 71
yurzui Avatar answered Oct 13 '22 00:10

yurzui