Angular 在属性值内呈现 HTML

huangapple go评论95阅读模式
英文:

Angular render HTML inside property values

问题

export const message {
  'comment.require.error2': '响应已选择为 <b>NO</b>,您必须提供评论以支持它',
}
<small class="lmn-text-danger">
  {{ message['comment.require.error2'] | raw }}
</small>
英文:

message.properties.ts

export const message {
&#39;comment.require.error2&#39;: &#39;The response has been chosen as &lt;b&gt;NO&lt;/b&gt;, you must provide comments to support it&#39;,
}

HTML

 &lt;small class=&quot;lmn-text-danger&quot;&gt;
     {{ message[&#39;comment.require.error2&#39;] }}
 &lt;/small&gt;

How can I render NO as bold, when I try to use this way it also renders HTML(&lt;b&gt;NO&lt;/b&gt;)

答案1

得分: 1

使用innerHTML来渲染字符串为HTML,而不是使用字符串插值来渲染为纯文本:

<small class="lmn-text-danger" [innerHTML]="message['comment.require.error2']"></small>

此外,由于这会向DOM添加元素,存在安全风险,建议使用DOMSanitizer进行安全处理。

使用管道的示例:https://stackoverflow.com/questions/47528311/angular-5-sanitizing-html-with-pipe

英文:

Use innerHTML to render string as HTML instead of plain text with string interpolation:

 &lt;small class=&quot;lmn-text-danger&quot; [innerHTML]=&quot;message[&#39;comment.require.error2&#39;]&quot;&gt;&lt;/small&gt;

Also, as this adds elements to the DOM, which poses security risk, it is advisable to sanitize it with DOMSanitizer

Example using pipe: https://stackoverflow.com/questions/47528311/angular-5-sanitizing-html-with-pipe

huangapple
  • 本文由 发表于 2023年6月29日 14:59:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定