Search code examples
angulareventemitter

Can you subscribe to events on an embedded view in Angular?


I am trying to pass data/events up through a chain of nested components using EventEmitters. However I think the way I solved one problem may be preventing this from happening.

I am creating an embedded view on one of the components so it doesn't mess up the table structure. So for that component, here is some relevant code:

@ContentChild(DataTableAddRecordComponent) adder: DataTableAddRecordComponent;
@ViewChild('dtAdder', { read: ViewContainerRef }) adderContainer: ViewContainerRef;

ngAfterContentInit(): void {
    if (this.adder && this.adderContainer) {
      this.adderContainer.createEmbeddedView(this.adder.templateRef);
    }

  }

and here is some HTML for the same component. Notice how the thing I'm trying to subscribe to an event on is ng-container instead of the actual component. Again this is so I don't get <data-table-adder> tags screwing up my table. But how can I catch events from that component when it's not in my template (or is there something else I'm missing)?

<table>
<tbody>
<tr><td>Some Junk</td></tr>
<ng-container #dtAdder (added)="onAdd($event)"></ng-container>
</tbody>
</table>

Solution

  • This turned out to be easy... you have the reference to the component and you can subscribe to the emitted event programmatically.

    if (this.adder && this.adderContainer) {
      this.adderContainer.createEmbeddedView(this.adder.templateRef);
      this.adder.added.subscribe(data => 
        this.add.emit(data));
    }