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

JavascriptJsonAngular

Javascript Problem Overview


Edit: a clarification for anyone who only skimmed the title, my question is about Angular 2, not 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>"

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

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

Javascript Solutions


Solution 1 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionR891View Question on Stackoverflow
Solution 1 - JavascriptSasxaView Answer on Stackoverflow