3

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.

4
  • And you are dynamically loading/feeding the string? That is - you can't directly control the contents of the string? Commented Nov 30, 2018 at 1:03
  • 1
    You could try sanitizing the HTML string, as explained in this answer. Commented Nov 30, 2018 at 1:04
  • Yes. The string is auto generated from the server by a third party. So no control over the string generation. Commented Nov 30, 2018 at 1:05
  • Thanks @ConnorsFan. Worked like a charm! Commented Nov 30, 2018 at 1:14

1 Answer 1

4

Use DomSanitizer

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

and in template,

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

STACKBLITZ DEMO

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.