javascript - how to convert a variable into HTML element with Angular
问题描述
I've a json file
{
"articles": [
{
"id": 1,
"title": "<h1>How to install Atom</h1>"
},
{
"id": 2,
"title": "<h1>Installing Boostrap</h1>"
}
]
}
I am using json-server
with angular 8
to read this json. As you can see title
field is supposed to be an html head tag when rendered on screen. But it is getting printed as it is. See, this is what I am trying to say.
. I want to convert this into heading-1 tag in run time. My app.component.html
is
<div id="data-container">
</div>
Hello
<table>
<tr *ngFor="let art of lstcomments">
<td>{{art.id}}</td>
<td>
document.querySelector('#data-container').innerHTML={{art.title}}
</td>
</tr>
</table>
</div>
<router-outlet></router-outlet>
My title
is stored in {{ art.title }}
. I tried creating a separate div
with id data-container
and used document.querySelector
but the whole code gets printed as a string. What should I do now.
解决方案
As mentionend in the official docs, Angular automatically sanitize HTML so you can't just put it in the template with a variabile. This is done to prevent different kind of attacks by allowing external actors to interact with your page and push content in your HTML.
For the HTML to be interpreted, you can bind it to the HTML property innerHTML
as in this example:
<span [innerHTML]="art.title"></span>
推荐阅读
- mysql - MySQL 全文不准确
- context-free-grammar - 看了两个问题,不知道怎么回答
- python - 基于Cox比例风险模型的失效时间预测
- php - 通过比较不同表中的其他两个字段将不同的字段插入表中
- tensorflow - conv2d 不起作用
- java - 有人可以帮助我通过方法组织这个,因为我不明白如何:
- javascript - 检查电子邮件输入验证后,如何使用我的按钮将用户重定向到另一个 HTML 页面?
- java - 为什么我的代码超过了时间限制 (leetcode104)
- r - 带有特殊字符的 rvest jump_to
- android - 列表到阵列适配器