Reputation: 2226
in an Angular component we can inject DomSanitizer and use it.
@component({..})
export class myComponent{
constructor(private sanitizer: DomSanitizer){
//now we can use this.sanitizer.bypassSecurityTrustHtml(..)
}
}
but how to use DomSanitizer without injecting it in the constructor?
//this is not a class, so it doesn't contain a constructor()
export function keepHtml(value: string){
sanitizer = new DomSanitizer(); //error: Cannot create an instance of an abstract class
return sanitizer.bypassSecurityTrustHtml(content);
}
I don't want to import DomSanitizer
into my class, and then pass it to keepHtml() as a second parameter.
I want the whole implementation done inside the functions file.
also I don't want to convert the function keepHtml() into a class method.
Upvotes: 2
Views: 1667
Reputation: 113
Using a service for this (Anton Rusak's reply on the original post) is the way to go, and allows reusability.
Quick example would be as follows:
import { Injectable } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Injectable({
providedIn: 'root'
})
export class ServiceUsedForWhatever {
constructor(
private sanitizer: DomSanitizer
) {}
sanitizeResource(multimediaResource) {
return this.sanitizer.bypassSecurityTrustResourceUrl(multimediaResource);
}
}
And in any component, import the service and use it as follows:
mediaToSanitize = this.dataService.sanitizeResource(originalMedia);
It could even be improved by adding a switchcase listening to a second parameter called, for example, mediaType, so that the function could use other methods such as bypassSecutiryTrustHtml or bypassSecurityTrustUrl.
Edit: the author did indicate they did not want to use it as an injection because it was probably being used in a common /functions file to extend methods to other components, and I get that approach. But chances are that your project has, or could have, a generic Service that does stuff that other components or even Services can benefit from (such as getting/setting a token). The example above would go nicely with a service like that.
Upvotes: 3
Reputation: 936
You may try to use the internal implementation of DomSanitizer like this:
import { ɵDomSanitizerImpl } from '@angular/platform-browser/';
export function keepHtml(value: string){
const sanitizer = new ɵDomSanitizerImpl(document);
return sanitizer.bypassSecurityTrustHtml(content);
}
However this is not a good way to go. The internal implementation might change in future and break your code.
Upvotes: 3