Blog>
Snippets

Injecting SVG with Angular's Sanitization

Safely inject raw SVG content into an Angular template using the DomSanitizer service to prevent XSS attacks and demonstrate how to bind it to the innerHTML property of an element.
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-svg-injector',
  template: '<div [innerHTML]="safeSvgContent"></div>'
})
export class SvgInjectorComponent {
  safeSvgContent: SafeHtml;
  
  constructor(private sanitizer: DomSanitizer) {
    const rawSvg = '<svg><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg>';
    this.safeSvgContent = this.sanitizeSvgContent(rawSvg);
  }

  sanitizeSvgContent(svgContent: string): SafeHtml {
    // Sanitize the raw SVG content
    return this.sanitizer.sanitize(SecurityContext.HTML, svgContent);
  }
}
This Angular component safely injects raw SVG content into the template. The DomSanitizer service is used to sanitize the SVG content before binding it to the innerHTML property of a div element in the template, mitigating the risk of XSS attacks.