0 day streak
javascript / intermediate
Snippet

Bypassing Security Trust for Dynamic SVG Content with DomSanitizer

Angular automatically sanitizes untrusted HTML and SVG bindings to prevent Cross-Site Scripting (XSS) attacks. When rendering trusted dynamic markup, DomSanitizer allows developers to explicitly mark content as safe using bypassSecurityTrustHtml, producing a SafeHtml wrapper that Angular will render directly.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Component, inject, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-safe-icon',
standalone: true,
template: `<div [innerHTML]="trustedSvg"></div>`
})
export class SafeIconComponent {
private sanitizer = inject(DomSanitizer);
rawSvgString = '<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="40"/></svg>';
get trustedSvg(): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(this.rawSvgString);
}
}
angular
Breakdown
1
private sanitizer = inject(DomSanitizer);
Injects Angular's built-in DomSanitizer service using the modern inject() function.
2
return this.sanitizer.bypassSecurityTrustHtml(this.rawSvgString);
Bypasses the built-in XSS security checks and wraps the raw SVG string into a trusted SafeHtml type.
3
template: `<div [innerHTML]="trustedSvg"></div>`
Binds the sanitized SafeHtml instance to innerHTML without triggering security warnings or stripped tags.