如何在打字稿中使用/显示带有html标签的字符串

时间:2019-03-27 04:26:52

标签: html typescript

var bannerText = stringFormat("This is my {0}test content{1} here", "<b>", "</b>");
<div>
    <p> {para1}</p>
    <p> {bannerText}</p>
</div>

打印html标签,而不是将其作为文本应用

观察到的输出

  

这是我的测试内容在这里

需要的输出

  

这是我的测试内容在这里

3 个答案:

答案 0 :(得分:1)

检查以下代码可能会帮助您。使用内部html

document.getElementById("name").innerHTML="This is <u>my test</u> sample"
<div id="name"></div>

答案 1 :(得分:0)

  

Observed output This is my <u>test content</u> here

您使用的任何方法都是转义 html,例如< / >

修复

您需要某些版本的 set HTML

例如React:dangerouslySetInnerHTML,Pure JS:使用innerHTML

警告

请注意,设置html会将您的应用暴露给XSS:https://en.wikipedia.org/wiki/Cross-site_scripting

答案 2 :(得分:0)

<div [innerHTML]="bannerText"></div>

但是,请记住Angular的docs about security,它表示为Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element.