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

问题描述 投票:0回答:1

用户输入文本为字符串:

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>
angular
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.