Alvin Saldanha
Alvin Saldanha

Reputation: 916

Displaying HTML String in div using innerHtml

I need to display raw HTML string using a div. I am assigning the HTML string to the innerHTML of a div like below

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

However if the html string contains multiline comments or inline styles they too are displayed as text. See the issue on Stack Blitz here.

Expected functionality is that the comments and inline style blocks should not be displayed. This is how it should be rendered.

Expected result

All the previous answers on Stack Overflow point to using div innerHTML. I know I am missing something trivial here, but I can't seem to figure out. Thanks in advance for the help.

Upvotes: 3

Views: 2494

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

Use DomSanitizer

  safeHtml(html) {
    return this._sanitizer.bypassSecurityTrustHtml(html);
  }

and in template,

  <div [innerHTML]="safeHtml(rawHTMLString)"></div>

STACKBLITZ DEMO

Upvotes: 4

Related Questions