Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Events and Variable to Dynamically created Component Angular 4

I've a dynamically created component in my Angular app as follows:

const factory = this.resolver.resolveComponentFactory<IMessage>(MessageComponent);
this.component = this.container.createComponent(factory);
this.component.instance.body = message;

It is equivalent to adding <message [body]="message"></message> in component's HTML.

Let's assume that, I want to achieve something like this in my dynamic component code:

<message [body]="message" #form="my-form" (change)="myFunction()"></message>

How do I bind these additional variable and change events inside by component's ts file?

like image 950
Sahil Purav Avatar asked Jan 30 '23 01:01

Sahil Purav


1 Answers

Input bindings and events outputs don't work automatically with dynamically created components. This is because the compiler creates the function that listens to child components events and the function that updates child component bindings based on the template it parses. Dynamic components are not specified in the template so the compiler doesn't create such functions. You can read here about these functions - The mechanics of property bindings update in Angular. The function name is updateDirectives.

You have to manually update the properties and subscribe to events:

this.component.instance.body = message;
this.component.instance.change.subscribe();

This means that child component can't use ngOnChanges lifecycle hook as it will never be triggered by Angular.

Also, query list bindings like these #form don't work as well. All you have access to is the instance of the component. So whatever directive exports itself as my-form should inject a host MessageComponent and attached the data associated with my-form to the component instance. Then parent component will be able to access it:

this.component.instance.formData;
like image 107
Max Koretskyi Avatar answered Feb 05 '23 18:02

Max Koretskyi