Created
May 24, 2018 06:24
-
-
Save Walgermo/ba3b58ade49eed1372e082d58ff750d7 to your computer and use it in GitHub Desktop.
Angular 2+ safe content pipe
This file contains 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, | |
SafeHtml, | |
SafeStyle, | |
SafeScript, | |
SafeUrl, | |
SafeResourceUrl | |
} from '@angular/platform-browser'; | |
/* | |
* Sanitizes by stripping all potentially dangerous content. | |
* Takes an input parameter any. | |
* Usage: | |
* htmlContent | safe: 'html' | |
* styleContent | safe: 'style' | |
* scriptContent | safe: 'script' | |
* urlContent | safe: 'url' | |
* urlContent | safe: 'resourceUrl' | |
* Example: | |
* <div [innerHTML]="content | safe: 'html'"></div> | |
*/ | |
@Pipe({ | |
name: 'safe' | |
}) | |
export class SafePipe implements PipeTransform { | |
constructor(protected sanitizer: DomSanitizer) { } | |
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl { | |
switch (type) { | |
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value); | |
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value); | |
case 'script': return this.sanitizer.bypassSecurityTrustScript(value); | |
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value); | |
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value); | |
default: throw new Error(`Invalid safe type specified: ${type}`); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment