Angular › Angular Security (XSS, Sanitization & CSP)

What is Angular's DomSanitizer service and when would you need to use it?

Intermediate

Answer

The DomSanitizer service lets you explicitly mark a value as safe to use in a specific context, like HTML, a URL, or a style, bypassing Angular's default automatic sanitization. It should only be used with content you fully trust, such as HTML generated by your own backend, never with raw, untrusted user input.
import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer) {}

getSafeHtml(html: string) {
  return this.sanitizer.bypassSecurityTrustHtml(html);
}
Real-world example A blogging platform uses DomSanitizer to safely display rich formatted article content written by trusted staff writers through a content management system, while completely avoiding this approach for anything submitted by anonymous website visitors.

Common follow-ups: What are the different trust contexts DomSanitizer supports, besides HTML?;What happens to a value if you forget to sanitize it when binding to something like innerHTML directly?