Reputation: 1316
I am looking for a way to use a custom pipe within my class. The custom pipe itself ( taken from here, thank you very much ) has a dependency injected ( the DomSanitizationService ).
import { Pipe, Inject, Injectable } from '@angular/core';
import {DomSanitizationService, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe {
constructor( protected _sanitizer: DomSanitizationService) { }
public transform(value: string, 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(`Unable to bypass security for invalid type: ${type}`);
}
}
}
I can use this pipe in my HTML-Template like this:
<div [innerHtml]="myHtmlContent | safe: 'html'"></div>
But when I want to use the pipe inside my code, e.g.:
getMyValue():string {
return new SavePipe( ).transform( this.myHtmlContent, 'html' );
// ^--- I should put something in here, I know
}
I get an error: Invalid number of Arguments, expected 1 argument
I know that when calling the new SavePipe(), I should pass the DomSanitizationService as an argument.
How can I do this? Or better: How can I change the Pipe so that it injects the DomSanitizationService on demand?
Upvotes: 1
Views: 1319
Reputation: 657781
If you create a class with new SomeClass
Angulars DI is not involved and you have to pass all parameters yourself.
You can inject DomSanitizationService
to the component where you call new SafePipe()
and then just pass the injected instance.
constructor(private sanitizer: DomSanitizationService) {}
...
someMethod() {
new SafePipe(this.sanitizer);
}
Upvotes: 2