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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With