Categories
Angular Answers

How to add innerHTML styling with Angular?

Spread the love

Sometimes, we want to add innerHTML styling with Angular.

In this article, we’ll look at how to add innerHTML styling with Angular.

How to add innerHTML styling with Angular?

To add innerHTML styling with Angular, we call sanitizer.bypassSecurityTrustHtml to allow style tag code to be rendered.

For instance, we write

import { DomSanitizer } from "@angular/platform-browser";

@Component({
  // ...
})
class SomeComponent {
  constructor(private sanitizer: DomSanitizer) {}

  transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
  }
}

to call this.sanitizer.bypassSecurityTrustHtml with the htmlTextWithStyle HTML string to return the HTML string that can be rendered in the template.

The returned HTML can include style attribute and elements so we can render the styles with [innerHTML].

Conclusion

To add innerHTML styling with Angular, we call sanitizer.bypassSecurityTrustHtml to allow style tag code to be rendered.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *