【问题标题】:Angular 2 partial html injection with DomSanitizerAngular 2 使用 DomSanitizer 进行部分 html 注入
【发布时间】:2017-12-29 14:16:15
【问题描述】:

用户输入文本为字符串:

i try to learn html and this is a <h1>title</h1>

我将字符串保存到类成员 然后我操纵字符串值和结果:

this.data = "<span style='color:red'>i try to learn html and this is a</span> <span style='color:green'><h1>title</h1></span>";

然后我将它传递给 getData 函数:

消毒剂是 DomSanitizer

getData(){
   return this.sanitizer.bypassSecurityTrustHtml(this.data);
}

因此html h1标签被解析为html元素

有没有办法将字符串的一部分视为“纯字符串”,这样他的内容就不会被翻译成新的 html 元素?例如 {{data}}

这是组件html:

<div [ngStyle]=getStyles() [innerHTML]="getData()"></div>

【问题讨论】:

  • 所以你想让span元素呈现为html而不是h1元素?
  • @Supamiu 没错
  • 绑定到一个函数是一个非常糟糕的主意。 innerHTML 将在每次运行更改检测时更新。而是将getData 的结果分配给一个字段并绑定到该字段。
  • “纯字符串”部分的预期行为是什么?
  • @GünterZöchbauer 预期的行为是将其视为不会被解析为 html 元素的字符串值:这将是红色:“我尝试学习 html,这是一个”,这将为绿色:“

    title

标签: angular


【解决方案1】:

您可以将标题字符串分配给另一个变量并在this.data 变量中调用它

this.title = "<h1>title</h1>";
this.data = `<span style='color:red'>i try to learn html and this is a</span> <span style='color:green'> ${this.title} </span>`;

在 html 中只需调用 data 变量。

<div [ngStyle]="getStyles()" [innerHTML]="data"></div>

【讨论】:

  • 在本例中,this.title 的值呈现为 html 元素而不是文本,因此它不起作用:(
猜你喜欢
  • 2017-02-12
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2012-02-05
  • 1970-01-01
  • 2017-01-19
相关资源
最近更新 更多