javascript / intermediate
Snippet
Sanitizing Untrusted User Markup with Security Pipes
Angular provides built-in defenses against Cross-Site Scripting (XSS) by automatically encoding untrusted values bound via innerHTML. When custom HTML rendering is required, wrapping DomSanitizer methods inside a dedicated pipe encapsulates sanitization logic and returns an explicitly trusted SafeHtml data type.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Pipe, PipeTransform } from '@angular/core';import { DomSanitizer, SafeHtml } from '@angular/platform-browser';@Pipe({name: 'sanitizeHtml',standalone: true})export class SanitizeHtmlPipe implements PipeTransform {constructor(private readonly sanitizer: DomSanitizer) {}transform(rawContent: string | null | undefined): SafeHtml {if (!rawContent || typeof rawContent !== 'string') {return '';}const cleanContent = rawContent.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');return this.sanitizer.bypassSecurityTrustHtml(cleanContent);}}
angular
Breakdown
1
constructor(private readonly sanitizer: DomSanitizer) {}
Injects Angular's DomSanitizer service to manage security context bypasses.
2
transform(rawContent: string | null | undefined): SafeHtml {
Implements PipeTransform to accept variable string inputs and output sanitized SafeHtml instances.
3
if (!rawContent || typeof rawContent !== 'string') {
Validates input types to prevent runtime errors when nullish or non-string values are passed.
4
return this.sanitizer.bypassSecurityTrustHtml(cleanContent);
Bypasses standard HTML escaping, informing Angular that the cleansed markup is safe for DOM injection.