Angular使用带有转义元素属性的innerHTML

时间:2017-09-08 15:11:45

标签: angular

嗨我有一个来自其他服务器的html respose:

<h3>Center Align</h3>\n<p style=\"text-align: center;\">This is a paragraph. It is center aligned. Center is, but nature, a fence sitter. A flip flopper. It has a difficult time making up its mind. It wants to pick a side. Really, it does. It has the best intentions, but it tends to complicate matters more than help. The best you can do is try to win it over and hope for the best. I hear center align does take bribes.</p>

当我使用 innerHTML 呈现为:

<h3>Center Align</h3>
<p>
This is a paragraph. It is center aligned. Center is, but nature, a fence sitter. A flip flopper. It has a difficult time making up its mind. It wants to pick a side. Really, it does. It has the best intentions, but it tends to complicate matters more than help. The best you can do is try to win it over and hope for the best. I hear center align does take bribes.
</p>

缺少<p>代码的转义属性,因此我有一个空<p>而不是<p style="text-align: center;">

有没有办法使用其属性呈现此内容?

1 个答案:

答案 0 :(得分:1)

使用DomSanitizer处理您的HTML。它默认是不安全的。

constructor(private s: DomSanitizer) {
  this.text = 'my HTML';
  this.text = s.bypassSecurityTrustHtml(this.text);
}

请参阅plunk