【问题标题】:Using ng-template reference in ngSwitch在 ngSwitch 中使用 ng-template 引用
【发布时间】:2017-05-25 15:39:58
【问题描述】:

我不想在每个*ngSwitchCase 块中编写html 代码,而是想添加对ng-template 的引用 从这个想法(来自角度文档):

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

想要这样做:

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

而不是这个:

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

【问题讨论】:

  • AFAIK 你不能使用带有ngSwitch 的模板块。出于好奇……你需要这个做什么?
  • 我没有在每个 ngSwitchCase 块中编写大量 html,也没有为这段 html 创建一个新组件,而是创建了 ng-templates 并在 ngSwitchCase 块中引用它们跨度>
  • 对结构指令和模板变量的情况有一些解释:weblogs.thinktecture.com/thomas/2017/05/…

标签: angular


【解决方案1】:

可以通过ngTemplateOutlet 实现。第二个模板也展示了传递上下文的能力。

<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>

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多