354

In my angular 4 app, I have a string like

comment: string;
comment = "<p><em><strong>abc</strong></em></p>";

When I serve this text in my html, like

{{comment}}

Then it displays:

<p><em><strong>abc</strong></em></p>

But I need to display the text "abc" in bold and italic form, like abc

How can I do this?

0

1 Answer 1

781

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Sign up to request clarification or add additional context in comments.

13 Comments

In Angular front-end, using [innerHTML] may lead to security faults, and thus should be disallowed. angular.io/guide/security.
@HongNguyen As I understand it, I think that article you shared explains that it is safer to use [innerHTML]. Check the live example.
FYI from angular docs: "Angular recognizes the value ([innerHtml]) as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."
this has a drawback: it won't apply css styles to the tags that are in the component css
@albanx you can add css styles by adding "encapsulation: ViewEncapsulation.None," to your Component. More info here: stackoverflow.com/questions/44210786/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.