Using ng-template reference in ngSwitch

时光总嘲笑我的痴心妄想 提交于 2019-12-23 03:16:25

问题


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:


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>


来源:https://stackoverflow.com/questions/44184507/using-ng-template-reference-in-ngswitch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!