Pass "content-projection" into recursive NGTemplateOutlet component?


I am trying to create a recursive component for a node-tree using NgTemplateOutlet.

I’m stuck at the part where I need the html that was passed into the component at top-level to be shown inside my recursive component..

I am basing my recursive component on this article, and this StackBlitz example.


<wt-nested-list [nodes]="topNodeTree">
  <div *nestedListNode="let node">
    <h1>{{ node.nodeName }}</h1>


<div class="wt-nested-list">

<ng-container *ngFor="let node of nodes">
  <!-- node -->
  <div class="wt-nested-list__node">
    <ng-container *ngTemplateOutlet="nodeTemplate; context: {$implicit: node}"></ng-container>
    <!-- child nodes of node -->
    <ng-container *ngIf="node.children">


How do I ge the the custom html ( <div *nestedListNode= ...etc ) from app.component.html to also be placed into the recursive part inside wt-nested-list.component.html ? (indicated by ???)

Here is a example that might help explain my problem


I would solve this by defining optional @Input property that I will pass for nested component:


class NestedListComponent {

  @Input() template: TemplateRef<any>;

  @ContentChild( NestedListNodeDirective, { read: TemplateRef } ) nodeTemplate;

Now, in template we need to make sure that at least one of these template exists:


<ng-container *ngTemplateOutlet="nodeTemplate || template; context: ..."></ng-container>
<wt-nested-list [nodes]="node.children" [template]="nodeTemplate || template">

Stackblitz Example

Answered By – yurzui

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.