Skip to content

Instantly share code, notes, and snippets.

@tnqsoft
Created May 31, 2017 10:27
Show Gist options
  • Save tnqsoft/ef540cacd655fbe55cde00c306b0c23c to your computer and use it in GitHub Desktop.
Save tnqsoft/ef540cacd655fbe55cde00c306b0c23c to your computer and use it in GitHub Desktop.
SafePipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
/*
* Trust pipe
* Usage:
* value | safe
*/
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
public transform(value: any, safeType: string = 'html'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (safeType) {
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: ${safeType}`);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment