Skip to content

Instantly share code, notes, and snippets.

@yoSteve
Last active June 26, 2019 16:27
Show Gist options
  • Save yoSteve/27b7dce81570da18bdae066d88528159 to your computer and use it in GitHub Desktop.
Save yoSteve/27b7dce81570da18bdae066d88528159 to your computer and use it in GitHub Desktop.
Angular Safe Pipe: Sanitize trusted inline url/html/style values. Safety first!
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
transform(value: string, type?: 'style' | 'html' | 'url'): any {
if (value) {
switch (type) {
case 'style':
return this.sanitizer.bypassSecurityTrustStyle(value);
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'url':
return this.sanitizer.bypassSecurityTrustUrl(value);
default:
return this.sanitizer.sanitize;
}
}
return null;
}
constructor(private sanitizer: DomSanitizer) {}
}
@yoSteve
Copy link
Author

yoSteve commented Jun 26, 2019

component.ts:
myStyleValue = 'width: 5rem; background-color: goldenrod';
myHtmlString = '<span>Look at me!</span>';

template.html:
<div [attr.style]="myStyleValue | safe: 'style'">
<div [innerHTML]="myHtmlString | safe: 'html'"></div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment