将innerHTML放置在元素中作为文本而不是html



我正在使用AngularJS构建信使应用程序。messagesData是包含消息类型和消息内容并由谁发送的数组。

当我使用这个函数时,它工作得很好,

但是当我在函数中输入html代码时html会应用到消息框

的例子:

input("<div>Hello</div>")

它在里面创建了一个div hello word但是我想让整个元素出现在消息

这就是我要讲的函数:

function dataToHtml(which){
//check if data = message
if(messagesData[which][0]=='message'){
//check if its user message or the other one
if(messagesData[which][1]=='mine'){
chatContainer.innerHTML+=
`
<div class="chat-message-box">
<div class="mine-message chat-message">${messagesData[which][2]}</div>
</div>
`
}else if(messagesData[which][1]=='other'){
chatContainer.innerHTML+=
`
<div class="chat-message-box">
<div class="other-message chat-message main-bg">${messagesData[which][2]}</div>
</div>
`
}
}
}

使用单向流语法属性绑定:

comment: string;
comment = "<p><em><strong>abc</strong></em></p>";
<div [innerHTML]="comment"></div>
angular会将该值识别为不安全的,并自动对其进行消毒,这样会移除标签,但会保留安全的内容,比如元素。https://angular.io/guide/security sanitization-example

最新更新