7

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.

1 Answer 1

12

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);
Sign up to request clarification or add additional context in comments.

2 Comments

how do i add a click listener on the instance ?
newComponent.location.nativeElement.addEventListener('click', myClickHandler.bind(this)) or @Hostlistener('click') myClickHandler(){...} inside the dynamic component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.