Dynamic pipe in Angular 2
Unfortunately I don't think so. It's the same as in angular1 where you have a function return a string for the dynamic Pipe you want.
Looking at the docs that's exactly how they show it as well.
https://angular.io/docs/ts/latest/guide/pipes.html
template: `
<p>The hero's birthday is {{ birthday | date:format }}</p>
<button (click)="toggleFormat()">Toggle Format</button>
`
Then in the controller:
get format() { return this.toggle ? 'shortDate' : 'fullDate'}
Alas, it could be worse! :)
Building on borislemke's answer, here's a solution which does not need eval()
and which I find rather clean:
dynamic.pipe.ts:
import {
Injector,
Pipe,
PipeTransform
} from '@angular/core';
@Pipe({
name: 'dynamicPipe'
})
export class DynamicPipe implements PipeTransform {
public constructor(private injector: Injector) {
}
transform(value: any, pipeToken: any, pipeArgs: any[]): any {
if (!pipeToken) {
return value;
}
else {
let pipe = this.injector.get(pipeToken);
return pipe.transform(value, ...pipeArgs);
}
}
}
app.module.ts:
// …
import { DynamicPipe } from './dynamic.pipe';
@NgModule({
declarations: [
// …
DynamicPipe,
],
imports: [
// …
],
providers: [
// list all pipes you would like to use
PercentPipe,
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { PercentPipe } from '@angular/common';
@Component({
selector: 'app-root',
template: `
The following should be a percentage:
{{ myPercentage | dynamicPipe: myPipe:myPipeArgs }}
`,
providers: []
})
export class AppComponent implements OnInit {
myPercentage = 0.5;
myPipe = PercentPipe;
myPipeArgs = [];
}
The easiest way to tackle this would be to not use the pipes in the HTML templates, but instead, inject the pipe into a component's constructor (using DI), then apply the transform functionally. This works quite well with an Observable map or similar rxjs streams.