Javascript Angular 2:如何在不向用户显示标签的情况下从 JSON 响应呈现 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34936027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:04:13  来源:igfitidea点击:

Angular 2: How do you render HTML from a JSON response without displaying the tags to the user?

javascriptjsonangular

提问by Josh

Edit:a clarification for anyone who only skimmed the title, my question is about Angular 2, not 1.

编辑:对只略读标题的人的澄清,我的问题是关于Angular 2,而不是 1。



I have a component template that is something like this:

我有一个类似这样的组件模板:

<div>{{ post.body }}</div>

The object is something like:

对象是这样的:

{
    "title": "Some Title",
    "body": "<p>The <em>post body</em>.</p>"
}

Instead of rendering the paragraph like:

而不是像这样渲染段落:

The post body

帖子体

it displays:

它显示:

"<p>The <em>post body</em>.</p>"

"<p>The <em>post body</em>.</p>"

Since it's such a common task, I looked for a built-in pipe like {{ post.body | safe }}but didn't see one.

由于这是一项如此常见的任务,我寻找了一个内置管道,{{ post.body | safe }}但没有看到。

Is there is an easy way to get that working? Is there a safe way to get that working?

有没有一种简单的方法可以让它发挥作用?有没有安全的方法来让它工作?

回答by Sasxa

In Angular2 you can use property bindingto access properties of DOM elements, in your case:

在 Angular2 中,您可以使用属性绑定来访问 DOM 元素的属性,在您的情况下:

<div [innerHTML]="post.body"></div>