0

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>
333Matt
  • 1,124
  • 2
  • 19
  • 29
  • what is `this.adder.templateRef`? – Max Koretskyi Dec 04 '17 at 19:49
  • If you look more closely at the code above you can see that adder is just a component declared as a contentchild. TemplateRef is a property of components- a reference to their view template - for creating these embedded views. https://angular.io/api/core/TemplateRef – 333Matt Dec 05 '17 at 18:24

1 Answers1

1

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));
}
333Matt
  • 1,124
  • 2
  • 19
  • 29