3

I am attempting to pass through html with inline styles as a variable to an angular component.

var htmlValue = "<div style="margin-left: 13px; font-size: large;" fxLayout="column" fxLayoutAlign="center start">
    Need Help?
  </div>"

However the inline style is removed when rending the code on the component.

<div [innerHtml]="htmlValue"></div>

Renders as:

<div>
  <div>
    Need Help?
  </div>"
</div>

Is there a way to stop this from happening

1 Answer 1

4

You need to utilize the DomSanitizer. With the sanitizer injected in the constructor, your htmlValue assignment would be updated to the following.

var htmlValue = this.sanitizer
    .bypassSecurityTrustHtml("<div style="margin-left: 13px; font-size: large;" fxLayout="column" fxLayoutAlign="center start">
    Need Help?
  </div>")

Working StackBlitz example.

WARNING

Angular stripping out the styles, etc initially is due to safety concerns, so do this cautiously. This should be used only when you can trust the html being injected. If the html is something that ultimately comes from user input, then this should be done very judiciously as the user could utilize this to inject unsafe code into your application.

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

2 Comments

i have same error. but my content is being fetched from api. how can i handle this.
@azhar, you will need to show some code. This should work for you as well.

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.