Search code examples
angularviewchildng-template

Pass data from child to parent when child is rendered through ng-template


I am using @ViewChild to create a child component, through a template reference variable. I would like to pass data from the dynamically created child to its parent, in any way, but preferably using the @Output decorator.

Is this possible in any manner?

Parent.html

<ng-template #childComponent></ng-template>

Parent.ts

@ViewChild("childComponent", { static: true, read: ViewContainerRef })
  myChildComponent: ViewContainerRef;
  componentRef: ComponentRef<any>;

createComponent() {
  const myChildComponentRef = this.myChildComponent;
  this.componentRef = myChildComponentRef.createComponent(ChildComponent);
  this.componentRef.changeDetectorRef.detectChanges();

Child.html

<div class="table-container">
  Some table here, populated by data from a server response
</div>

Child.ts

@Output() data = new EventEmitter<any[]>();

constructor() { }

outputData() {
  this.data.emit(serverResponse);
}

I have used @Output before and I am aware that the parent's method should be bound to the child's event, within the child's selector in the parent's template. Since I do not have the child's selector because of the ng-template, I cannot think of good way to make this happen.


Solution

  • Event emitters are just glorified observables.

    When you create your child component, you can then call

    this.componentRef.data.subscribe(...);
    

    Don't forget to unsubscribe to avoid memory leaks too !