Search code examples
angularangular2-template

using ng-content in ng-template


Is it possible to use <ng-content> (and its select option) inside a <ng-template> or does it only works within a component ?

<ng-container *ngTemplateOutlet="tpl">
  <span greetings>Hello</span>
</ng-container>

<ng-template #tpl>
  <ng-content select="[greetings]"></ng-content> World !
</ng-template>

The above code does just render World ! :(

Here is the live example


Solution

  • As far as i know it is not possible using ng-content, but you can provide parameters to the template. So it's possible to pass another NgTemplate, which can again be used with an NgTemplateOutlet inside the original template. Here's a working example:

    <ng-container *ngTemplateOutlet="tpl, context: {$implicit: paramTemplate}">
    </ng-container>
    
    <ng-template #paramTemplate>
      <span>Hello</span>
    </ng-template>
    
    
    <ng-template #tpl let-param>
      <ng-container *ngTemplateOutlet="param"></ng-container> World !
    </ng-template>
    

    Actually it is even possible to pass multiple templates to the original template:

    <ng-container *ngTemplateOutlet="tpl, context: {'param1': paramTemplate1, 'param2': paramTemplate2}">
    </ng-container>
    
    <ng-template #paramTemplate1>
      <span>Hello</span>
    </ng-template>
    
    <ng-template #paramTemplate2>
      <span>World</span>
    </ng-template>
    
    
    <ng-template #tpl let-param1="param1" let-param2="param2">
      <ng-container *ngTemplateOutlet="param1"></ng-container>
      <ng-container *ngTemplateOutlet="param2"></ng-container>
    </ng-template>