Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 927
faguilera85 Avatar asked Oct 14 '16 15:10

faguilera85


1 Answers

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);
like image 134
Günter Zöchbauer Avatar answered Nov 11 '22 09:11

Günter Zöchbauer