我在 Angular 2 中有一种奇怪的用例,我有一些内容包含常规 html 标签和自定义 html 标签。我想呈现常规 html 标签并将自定义 html 标签显示为纯文本。例如
the <CUSTOM_TAG>boy</CUSTOM_TAG> went to the <b>store</b>
应该有<CUSTOM_TAG>boy</CUSTOM_TAG>
就像您在上面看到的那样显示为纯文本,但是 <b>store</b>
应显示为 store,即实际呈现粗体标记。
当我尝试插入 html 的通常方式时,即
<div [innerHtml]="myHtml"></div>
由于自定义标签,我收到清理错误。当我修复清理错误时 done here它只是去掉了我也不想要的自定义标签。是否可以将自定义标签显示为纯文本并呈现常规 html 标签?
最佳答案
如果已知所有可能的自定义标签,您可以在将字符串传递给 [innerHTML]
之前对它们进行编码捆绑。方法encodeCustomTags
在以下代码片段中使用正则表达式替换 <customTag>
与 <customTag>
:
private customTags = [
"CUSTOM_TAG",
"otherTag",
];
myHtml = this.encodeCustomTags("the <CUSTOM_TAG>boy</CUSTOM_TAG> went to the <b>store</b>");
private encodeCustomTags(html: string): string {
let regex: RegExp;
for (let tag of this.customTags) {
regex = new RegExp(`<(/?)${tag}>`, "gi");
html = html.replace(regex, `<$1${tag}>`)
}
return html;
}
参见 this stackblitz用于演示。
关于html - 如何在 innerHtml 中将自定义 html 标签显示为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190314/