【问题标题】:How to Interpolate the Tag Name in Angular Template如何在 Angular 模板中插入标签名称
【发布时间】:2019-12-20 08:01:11
【问题描述】:

我有一些 api 数据..Json 格式的 HTML 标记:

[
  {
     type: 'p',
     attributes: [...],
     children: [{...},{...}]
  }
]

我想在一个角度模板中呈现它。 由于标签的名称来自api,我需要插入标签名称。

我试过这个:

<ng-container *ngFor="let el of body">
   <{{el.type}}> foo bar</{{el.type}}>
</ng-container>

但得到“意外的结束标记“{{el.type}}”。

预期输出:

<p> foobar</p>

而且我不想使用 innerHtml 指令。

【问题讨论】:

  • 它是一个对象数组。尝试 {{el[0].type}} 获取第一种类型的 el 对象
  • 更新了 sn-p。我已经在对象级别了。
  • 我想使用 type 属性作为 html 标签
  • 你为什么不想使用[innerHTML]?我知道一个可能的原因,但我想知道你的原因是什么......

标签: angular angular-template


【解决方案1】:

在 js 中构造你的 html 并将其分配给局部变量,最后将该值传递给 innerhtml,它将按您的预期呈现

【讨论】:

    【解决方案2】:

    您可以简单地使用 [innerHTML] 指令来完成它。

    【讨论】:

      【解决方案3】:

      如果不想使用 [innerHTML],可以使用 [textContent]。

      【讨论】:

      • 您将无法使用 textContent 在 DOM 上呈现 HTML 内容。
      • 是的,只能显示内容
      猜你喜欢
      • 2012-01-04
      • 2019-10-27
      • 2011-01-12
      • 2010-09-20
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      相关资源
      最近更新 更多