2

I have a question about angular2 pipe. I want to get pipes as return value depending on schema:string. I think 2 way to get it, but both are not working.

page.html

<p>{{value | getSchema(value, schema)}}</p>

page.ts

getSchema(value, schema){
    if(schema == 'Currency'){
        return "currency: 'USD':true";
    } else if(schema == 'Number'){
        return 'number';
    }
}

or

page.html

<p>{{getSchema(value, schema)}}</p>

page.ts

getSchema(value, schema){
    if(schema == 'Currency'){
        return value + "| currency: 'USD':true";
    } else if(schema == 'Number'){
        return value + '| number';
    }
}

is there any ideas? Thanks.

Daisy
  • 89
  • 2
  • 9
  • Why not put the switch logic inside a pipe that takes arguments instead? It will be clearer and probably not as bad performance wise. – masimplo Nov 25 '16 at 20:14

1 Answers1

2

You can use a custom pipe that calls to another pipe depending on the parameter

@Pipe({name: 'genericPipe'})
class MyPipe {
  constructor(private currPipe:CurrencyPipe, private numberPipe:NumberPipe) {}
  transform(value, schema) {
    if(schema == 'Currency') {
      return this.currPipe.transform(value);
    } else {
      return this.numberPipe.transform(value);
    }
  }
}
<p>{{value | genericPipe:schema}}</p>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567