How to render string with html tags in Angular 4+?
To render HTML from a string securely in Angular, pull in DomSanitizer
and employ bypassSecurityTrustHtml
:
Now sanitizedHtml
is a getter emitting the sanitized html content, thus ensuring the dynamic content is safe from nasties such as XSS threats.
But remember, kids, with great power (like bypassSecurityTrustHtml
) comes great responsibility. This tool assumes you're best pals with the source of the content you're absolving. For content come from user input, Angular’s trusty sanitizer is your best sidekick!
Sanitization process in Angular
Angular's got your back with XSS issues. By default, any string duct-taped to [innerHTML]
, is sanitized by Angular removing potentially harmful tags like <script>
or triggers running JavaScript code. While this functions as a crucial defense shield, improper handling can strip out legitimate HTML.
When should you bypass sanitization?
Dodge the automatic sanitizer with the bypassSecurityTrustHtml
function discerningly. Here are a couple of situations where bypassing may be apt:
- When displaying responses from third-party APIs formatted as HTML.
- Showcasing rich-text content derived from your CMS.
User-generated content: Handle with care!
User generated content can be tricky. To steer clear of XSS threats, don’t bind user-generated inputs with [innerHTML]
directly, always sanitize first. Considering alternatives like Markdown flavor for user inputs, or a strong sanitizer library like DOMPurify may save you from security woes.
Angular's security wristband: DomSanitizer
The utility belt of DomSanitizer
DomSanitizer
is a security workhorse in Angular. It supports numerous sanitation methods like sanitize()
, bypassSecurityTrustStyle()
, bypassSecurityTrustScript()
, bypassSecurityTrustUrl()
, and bypassSecurityTrustResourceUrl()
. Out of these, you would majorly use bypassSecurityTrustHtml()
for rendering HTML.
Preserving styles during sanitization
To keep the styles intact, you can sanitize the CSS separately and include it in the component styles. If there are inline styles, they can be easily maintained using [ngStyle]
. No need to bypass any sanitizer!
Alternatives to innerHTML
In case [innerHTML]
doesn't cover your needs, there are other native DOM manipulation methods for complex scenarios. Methods from Renderer2
or ElementRef
can provide you more control but should also come with a "Handle with care" label.
Was this article helpful?