Sahil Purav
Sahil Purav

Reputation: 1354

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?

Upvotes: 4

Views: 4524

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105507

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;

Upvotes: 8

Related Questions