我在我的网络应用中写了一个聊天框,而聊天div中的HTML帖子也没有像我预期的那样显示。它们以字符串形式显示,我希望HTML在聊天中呈现。不知道为什么他们是字符串形式,我根本不过滤字符串。我怎样才能呈现HTML?
HTML:
<div *ngFor="let x of serverObj.values">
<div *ngFor="let y of x.shouts">
<p>
<span style="font-family: initial; font-size: x-small; font-
weight: bold;">{{y.shoutTime}}</span>
<span style="font-size: small; font-weight: bold;">{{y.shoutUser}}</span>
<span>: {{y.shoutContent}}</span>
</p>
</div>
</div>
<form name="shoutbox">
<textarea
style="color: black;"
id="shoutbox_input"
#textArea
(keyup.enter)="serverObj.addShout(displayName(), textArea.value)"
(keyup.enter)="textArea.value = ''"
></textarea>
<p><button id="shout_submit_button" type="button" (click)="serverObj.addShout(displayName(), textArea.value)">Sumbit</button></p>
</form>
数据接口:
shouts: [{
shoutUser: string;
shoutContent: string;
shoutTime: Date;
}];
服务器类(将呼叫添加到数据库中):
public addShout(user: string, content: string): void{
//setting the proper time
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function nonMilitary(j){
return ((j + 11) % 12 + 1);
}
function amPM(k){
if(k >= 12){
return "PM";
}
else return "AM";
}
let date = new Date();
let hours = date.getHours();
let time = "(" + addZero(nonMilitary(hours)) + ":" +
addZero(date.getMinutes()) + " " + amPM(hours) + ")";
//TODO add id calling variable to hold the current day.
let day = ServerData.findOne({id: "Mark"});
ServerData.update(day._id, { $push: { shouts: { shoutUser: user,
shoutContent: content, shoutTime: time }}});
}
聊天OutPut:
(11:58 AM) PizzaLord : <img src="https://www.shabboshouse.org/wp-
content/uploads/2015/11/rocks2.jpg"/>
(12:03 PM) PizzaLord : shout
(12:08 PM) PizzaLord : <a href="www.google.com">Google.com website</a>
感谢您的帮助。
答案 0 :(得分:1)
如this article中所述,插值会导致内容被转义,HTML标记将以纯文本形式显示。
而不是使用插值:
<span>: {{y.shoutContent}}</span>
您可以使用数据绑定设置innerHTML
属性,如this stackblitz所示:
<span [innerHTML]="': ' + y.shoutContent"></span>