Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 970
Lulutho Mgwali Avatar asked Jul 07 '26 23:07

Lulutho Mgwali


1 Answers

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.

like image 166
peinearydevelopment Avatar answered Jul 10 '26 15:07

peinearydevelopment



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!