How to send a Pipe to component

Viewed 322

There is a way to send a Pipe to Component? I have a component that displays data, and I want to let the user choose which pipe he wants to use to display the data, for example:

<app-my-component value="abcde" [pipe]="UpperCasePipe"></app-my-component>
<app-my-component value="0.95" [pipe]="PercentPipe"></app-my-component>
<app-my-component [value]="[1,2,3,4]" [pipe]="MySummarizePipe"></app-my-component>

So, what I need is something like this:

@Component({
  selector: 'app-my-component',
  template: `
    <span>{{value|pipe}}</span>
  `
})
export class MyComponent {
    @Input() value: any;
    @Input() pipe: any;
}
2 Answers

I don't think there is a way to achieve what you are trying to do.

Why not just use the pipe while passing the value as follows:

<app-my-component [value]="'abcde' | UpperCasePipe"></app-my-component>
<app-my-component [value]="0.95 | PercentPipe"></app-my-component>
<app-my-component [value]="[1,2,3,4] | MySummarizePipe"></app-my-component>

Don't think you can use the inline template syntax shorthand like you are trying to do, but you could do something like the following (note though that @Bunyamin Coskuner's answer is probably more idiomatic and flexible).

@Component({
  selector: 'app-my-component',
  template: `
    <span>{{value}}</span>
  `
})
export class MyComponent {
    private _value: any;
    @Input()
    set value(val: any) {
      this._value = val;
    }
    get value(): any {
      if (this.pipe != null) {
        return this.pipe.transform(this._value);
      }
      return `${this._value}`;
    }
    @Input() pipe: PipeTransform;
}
Related