Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 853
R891 Avatar asked Jan 21 '16 23:01

R891


People also ask

How do I display HTML inside an angular binding?

To add HTML that contains Angular-specific markup (property or value binding, components, directives, pipes, ...) it is required to add the dynamic module and compile components at runtime. This answer provides more details How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

How do I render a string with HTML tag in angular 8?

To render a html string in angular, we can use the innerHTML property by binding a string to it. The innerHTML property sanitizes the html, so that your app is safe from the cross-site scripting attacks(XSS).

What is innerHTML in angular?

The innerHtml attribute is a standard HTML element attribute to which Angular 14 can bind with square brackets i.e [ & ] .

What is render tag in HTML?

Rendering tags are text strings embedded in the server response file HTML source code. A rendering tag has this general form: {{ tag }} {{ tag (parameter-list) }}


1 Answers

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

<div [innerHTML]="post.body"></div> 
like image 174
Sasxa Avatar answered Oct 16 '22 07:10

Sasxa