Lulutho Mgwali
Lulutho Mgwali

Reputation: 903

Passing innerHtml with inline styles (Angular 10)

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

Upvotes: 3

Views: 4289

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11474

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.

Upvotes: 4

Related Questions