admin管理员组

文章数量:1291834

I'm dynamically creating ponents inside appponent.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 ponent so it listens to the onDateRangeChange event and executes the dateRangeChanged(event) method defined inside the appponent.ts ponent.

I originally used this ponent this way inside the appponent.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.

I'm dynamically creating ponents inside app.ponent.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 ponent so it listens to the onDateRangeChange event and executes the dateRangeChanged(event) method defined inside the app.ponent.ts ponent.

I originally used this ponent this way inside the app.ponent.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.

Share Improve this question edited Oct 14, 2016 at 15:38 Günter Zöchbauer 658k233 gold badges2.1k silver badges1.6k bronze badges asked Oct 14, 2016 at 15:30 faguilera85faguilera85 1451 gold badge4 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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

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

本文标签: javascriptAdd event binding to dynamically created componentsStack Overflow