简介
angular 2+ 支持使用 [innerhtml]
属性绑定来渲染 html。如果你使用插值,它会被视为字符串。
本文将介绍如何使用 [innerhtml]
以及一些注意事项。
先决条件
如果你想跟着本文学习,你需要:
- 对 angular 插值和属性绑定有一定了解会更有帮助。
第一步 — 使用 innerhtml
假设你正在处理一个包含纯文本和 html 实体和元素混合的字符串的组件:
export class examplecomponent { htmlstr: string = 'plain text example & <strong>bold text example</strong>'; }
让我们考虑一个在这个字符串上使用插值的模板:
<div>{{ htmlstr }}</div>
编译后,这段代码将产生以下结果:
plain text example & <strong>bold text example</strong>
html 实体和 html 元素没有被渲染。
现在,让我们考虑一个在这个字符串上使用 [innerhtml] 属性绑定的模板:
<div [innerhtml]="htmlstr"></div>
重新编译后,这段代码将产生以下结果:
plain text example & bold text example
注意到 html 实体和 html 元素被渲染了。
第二步 — 理解限制
渲染 html 通常会引入跨站脚本攻击(xss)的潜在风险。渲染的 html 可能包含恶意脚本,构成安全问题。
解决 xss 的一种方法是限制 html 元素和属性的种类,只允许一组已知的“安全”元素和属性。
在幕后,[innerhtml] 使用 angular 的 domsanitizer,它使用一组经过批准的 html 元素和属性。
这将限制你的 [innerhtml] 值不能使用 <script> 和 <style> 标签以及 style 属性。在选择使用 [innerhtml] 时要牢记这一限制。
结论
在本文中,你了解了 angular 2+ 中 [innerhtml]
属性绑定的用法。它将渲染字符串中包含的 html 标记。
到此这篇关于在angular中使用innerhtml属性绑定的方法的文章就介绍到这了,更多相关angular innerhtml属性绑定内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论