Last active
June 26, 2019 16:27
-
-
Save yoSteve/27b7dce81570da18bdae066d88528159 to your computer and use it in GitHub Desktop.
Angular Safe Pipe: Sanitize trusted inline url/html/style values. Safety first!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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>