107

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?

6

1 Answer 1

220

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

<div [innerHTML]="post.body"></div>
Sign up to request clarification or add additional context in comments.

10 Comments

@CSchulz then what should be the secure way of doing it
You should only do it if you are sure that the source is trusted.
If you bind to html with [innerHTML]="yourHtml" in Angular 4 it will sanitize the string and remove any <script> tags: angular.io/guide/security#sanitization-and-security-contexts
@ibgib yup you don't need it anymore, Angular now sanitizes html content by default: angular.io/guide/security#sanitization-and-security-contexts
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.