Using ng-template reference in ngSwitch

Viewed 4366

Instead of writing the html code in each *ngSwitchCase block, I want to add a reference to a ng-template took the idea from this (from angular docs):

<div *ngIf="show; then thenBlock; else elseBlock">this is ignored</div>
<ng-template #primaryBlock>Primary text to show</ng-template>

want to do this:

<div [ngSwitch]="switchVar">
  <div *ngSwitchCase="1; then myTemplate"></div>
  <div *ngSwitchDefault>output2</div>
</div>
<ng-template #myTemplate>HTML TEXT</ng-template>

instead of this:

<div [ngSwitch]="switchVar">
  <div *ngSwitchCase="1">HTML TEXT</div>
  <div *ngSwitchDefault>output2</div>
</div>
1 Answers

Can be achieved with ngTemplateOutlet. Second template also demonstrates ability of passing context.

<div [ngSwitch]="switchVar">
  <div *ngSwitchCase="1">
    <ng-container *ngTemplateOutlet="tmplFirst"></ng-container>
  </div>
  <div *ngSwitchDefault>
    <ng-container *ngTemplateOutlet="tmplSecondWithContext; context: {bar: 42}"></ng-container>
  </div>
</div>

<ng-template #tmplFirst>HTML TEXT</ng-template>
<ng-template #tmplSecondWithContext let-foo="bar">Output: {{foo}}</ng-template>
Related