html - 如何在 innerHtml 中将自定义 html 标签显示为纯文本

标签 html angular

我在 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>&lt;customTag&gt; :

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, `&lt;$1${tag}&gt;`)
  }
  return html;
}

参见 this stackblitz用于演示。

关于html - 如何在 innerHtml 中将自定义 html 标签显示为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190314/

相关文章:

jquery mobile data-rel=背部麻烦

javascript - 我怎样才能重用功能而不是不断重复它?

jQuery - 添加一个类并在 500 毫秒后将其删除

jquery scrollTop 偏移问题

Angular 2 : view. setLocal ('\$implicit' , change.item);弃用什么?

c# - 如何将字符串传递给 Angular 中的发布请求?

Angular 警告 "Warning:Can' t 解析所有参数...”

php - 如何在html文本区域中逐句获取字符串

angular2-multiselect-dropdown 在下拉列表中显示 id 和 itemName

javascript - 如何将 getter 值绑定(bind)到 HTML 中?