How to render string with html tags in Angular 4+? [duplicate]
Asked Answered
T

1

342

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?

Taught answered 27/2, 2018 at 16:15 Comment(0)
F
760

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."

Firry answered 27/2, 2018 at 16:20 Comment(13)
In Angular front-end, using [innerHTML] may lead to security faults, and thus should be disallowed. angular.io/guide/security.Cota
@HongNguyen As I understand it, I think that article you shared explains that it is safer to use [innerHTML]. Check the live example.Debauchee
Thanks, but when my HTML be render, the string html generated, show as string, not Input or something like that. what should I do?Yenta
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."Outgo
can i open it in external browser... my inner html is link, i need to when click it open external browser new page. ? how can i do it, my anguler app , run using jx browser.Toilworn
@Toilworn yes if your innerhtml has <a target="_blank" href="google.com">Click here</a> tag. This should workEsteban
this has a drawback: it won't apply css styles to the tags that are in the component cssNoctambulism
@Noctambulism you can add css styles by adding "encapsulation: ViewEncapsulation.None," to your Component. More info here: #44211286Exit
Adding ng-bind-html="value" helped me.Displant
For simple html content we can use directly <div [innerHtml]="htmlContent"></div>, But if you want to use complex html and styles need to use the safeHtml pipes like this <div id="previewDoc" [innerHTML]="previewDoc | safeHtml" class="preview"></div> and we need to create the safeHtml pipe.Throne
@HongNguyen useless comment. disallow and HOW to do that? if projects ask us to do it, what is replacement then?Ratchford
@AylaWinters, It is not advisable to use "encapsulation: ViewEncapsulation.None" as it affects your global styling which me result in disturbed CSS for other components as wellTuscany
@Pipe({ name: "safeHtml" }) export class SafeHtmlPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(value) { return this.sanitizer.bypassSecurityTrustHtml(value); } }Elemental

© 2022 - 2024 — McMap. All rights reserved.