Created
December 23, 2022 18:59
-
-
Save DanielKucal/0cc13376efe3232b07845a8015125b14 to your computer and use it in GitHub Desktop.
safeHtml, safeStyle, safeScript, safeUrl and safeResourceUrl pipes included in a SafeResourceModule
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 { CommonModule } from '@angular/common'; | |
import { Injectable, NgModule, Pipe, PipeTransform } from '@angular/core'; | |
import { | |
DomSanitizer, | |
SafeHtml, | |
SafeResourceUrl, | |
SafeScript, | |
SafeStyle, | |
SafeUrl, | |
} from '@angular/platform-browser'; | |
@Injectable() | |
abstract class AbstractPipe { | |
constructor(protected domSanitizer: DomSanitizer) {} | |
public abstract transform(value: unknown): unknown; | |
} | |
@Pipe({ | |
name: 'safeHtml', | |
}) | |
class SafeHtmlPipe extends AbstractPipe implements PipeTransform { | |
transform(html: string): SafeHtml { | |
return this.domSanitizer.bypassSecurityTrustHtml(html); | |
} | |
} | |
@Pipe({ | |
name: 'safeStyle', | |
}) | |
class SafeStylePipe extends AbstractPipe implements PipeTransform { | |
transform(style: string): SafeStyle { | |
return this.domSanitizer.bypassSecurityTrustStyle(style); | |
} | |
} | |
@Pipe({ | |
name: 'safeScript', | |
}) | |
class SafeScriptPipe extends AbstractPipe implements PipeTransform { | |
transform(script: string): SafeScript { | |
return this.domSanitizer.bypassSecurityTrustScript(script); | |
} | |
} | |
@Pipe({ | |
name: 'safeUrl', | |
}) | |
class SafeUrlPipe extends AbstractPipe implements PipeTransform { | |
transform(url: string): SafeUrl { | |
return this.domSanitizer.bypassSecurityTrustUrl(url); | |
} | |
} | |
@Pipe({ | |
name: 'safeResourceUrl', | |
}) | |
class SafeResourceUrlPipe extends AbstractPipe implements PipeTransform { | |
transform(resourceUrl: string): SafeResourceUrl { | |
return this.domSanitizer.bypassSecurityTrustResourceUrl(resourceUrl); | |
} | |
} | |
const pipes = [SafeUrlPipe, SafeHtmlPipe, SafeStylePipe, SafeScriptPipe, SafeResourceUrlPipe]; | |
@NgModule({ | |
declarations: [...pipes], | |
imports: [CommonModule], | |
exports: [...pipes], | |
}) | |
export class SafeResourceModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment