【问题标题】:Can angular templates be variable?角度模板可以是可变的吗?
【发布时间】:2018-06-22 17:20:05
【问题描述】:

我有一个在我的组件中声明的变量,我们称之为“myVar”。根据这个变量,我想显示某个 ng-template。这是一个示例组件模板:

<div *ngIf="myVar; then myVar; else nothing"></div>
<ng-template #foo>My Foo-Content</ng-template>
<ng-template #nothing>No Content</ng-template>

有没有可能使这项工作?我希望“myVar”为空或名称“foo”,但上面的代码当然不会评估“myVar”。

或者有没有办法解决这个问题?在我的实际应用程序中,“myVar”有大约 10 个不同的值,但内容不足以使其成为自己的组件。

我必须为此制作 10 个不同的 *ngIf 吗? :(

【问题讨论】:

  • @JBNizet 这是个好主意,而且它的工作原理就像一个魅力!如果您创建一个小答案,我会接受。

标签: angular typescript angular6 angular-ng-if


【解决方案1】:

NgSwitch 看起来就是您要找的东西。

    <div [ngSwitch]="myVar">
      <div *ngSwitchCase="'Foo'">
        Content
      </div>
      <div *ngSwitchCase="'Bar'">
        Content
      </div>
      <div *ngSwitchDefault>
        Empty or fallback
      </div>
    </div>

【讨论】:

  • 我添加了我的示例代码。令我非常尴尬的是,我什至不知道 ngSwitch。这很棒,并且还可以捕获在找不到模板时可能发生的任何异常。非常感谢。
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2023-03-07
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2019-10-29
相关资源
最近更新 更多