使用DomSanitizer进行Angular 2部分html注入

时间:2017-12-29 14:16:16

标签: angular

用户输入文本为字符串:

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

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

这是组件html:

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

1 个答案:

答案 0 :(得分:0)

您可以将标题字符串分配给另一个变量,并在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>