faguilera85
faguilera85

Reputation: 145

Add event binding to dynamically created components

I'm dynamically creating components inside app.component.ts using the ViewContainerRef.createComponent() method, which returns a ComponentRef object.

let newComponent:ComponentRef<any> = this.filtersSection.createComponent(MyDateRangeComponent);

I need to dynamically add an event listener to this component so it listens to the onDateRangeChange event and executes the dateRangeChanged(event) method defined inside the app.component.ts component.

I originally used this component this way inside the app.component.html:

<my-daterange (onDateRangeChange)="dateRangeChanged($event)"></my-daterange>

I've found that this could be achieved using the Renderer class but I couldn't make this working:

this.renderer.listen(newComponent, 'click', (event) => {
    // Do something with 'event'
    console.log(event);
});

Any help with this would be really appreciated.

Upvotes: 7

Views: 4261

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657506

Using ComponentRef.instance allows you to access the component instance and with this you can subscribe to the EventEmitter:

newComponent.instance.onDataRateChange.subscribe(evt => this.result = evt);

Upvotes: 12

Related Questions