Skip to content

Instantly share code, notes, and snippets.

@blakazulu
Created January 25, 2021 14:01
Show Gist options
  • Save blakazulu/7d75721b3859a30aeb90db2c66a87abb to your computer and use it in GitHub Desktop.
Save blakazulu/7d75721b3859a30aeb90db2c66a87abb to your computer and use it in GitHub Desktop.
Angular CMS
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer, SafeHtml, SafeResourceUrl, SafeScript, SafeStyle, SafeUrl} from '@angular/platform-browser';
export type SafePipeType
= 'html'
| 'style'
| 'script'
| 'url'
| 'resourceUrl';
@Pipe({
name: 'safe',
pure: true
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {
}
public transform(value: string, type: SafePipeType): 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(`SafePipe unable to bypass security for invalid type: ${type}`);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment