How to pass template from inside child component to parent in Angular?

506 Views Asked by At

It is widely known that in Angular, we create templates in a host component like this:

  <ng-template #itemTemplate let-item>
    <div>
      {{ item.name }}
    </div>
  </ng-template>

And then pass that template to a child template:

  <app-child-component [item]='someItem' [item-template]="itemTemplate">
  </app-child-component>

The child component has this in its declaration:

  class ChildComponent {
    @Input('item-template') itemTemplate!: TemplateRef<any>
  }

And in its HTML, we have this:

<div>
  <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }">
  </ng-container>
</div>  

The template we put on the parent would show up wherever we need it to within the child component.

Is it possible to flip this so that we have a template inside a child component, and we would somehow expose it to the parent so that the parent can render it anywhere?

Suppose I have a child component and I want to build the <ng-template> inside of it. I want to expose it to the parent component so that it can place it anywhere on the parent component.

In the child component, I'd declare:

  class ChildComponent {
     templateToExposeToParent!: TemplateRef<any>
  }

And in its markup, I'd declare:

<ng-template #templateToExposeToParent>
   <!-- any content I want -->
</ng-template>`

So in the parent's markup, I'd write

  <app-child-component #childComponent>
  </app-child-component>
  <!-- other html to physically separate the template from childComponent -->
  <ng-container ngTemplateOutlet='childComponent.templateToExposeToParent'>
  </ng-container>

I set this up in an app, and the parent page does NOT show the template from inside childComponent.

Is this possible? Am I missing something?

I'd appreciate any help on this.

0

There are 0 best solutions below