Search code examples
angularfilterpipecurrency

Angular2 Pipe to convert currency


I have created a method to convert currency using a api, which looks as follows,

 exchange(Input: string, Output: string, value: number): number {
        let inputRate = this.currencyStorage.getCurrencyRate(cnput);
        let outputputRate = this.currencyStorage.getCurrencyRate(Output);
        return value/ inputRate * outputputRate;
    }

How can i create a pipe out of this which can be used throughout the application to convert currency ?


Solution

  • @Pipe({name: 'currConvert'})
    export class CurrConvertPipe implements PipeTransform {
      constructor(private currencyStorage:MyCurrencyStorage) {}
    
      transform(value: number, Input: string, Output: string): number {
        let inputRate = this.currencyStorage.getCurrencyRate(cnput);
        let outputputRate = this.currencyStorage.getCurrencyRate(Output);
        return value/ inputRate * outputputRate;
      }
    }
    

    register it with a modules declarations and use it like

    {{123 | currConvert:456 /*input*/:789 /*output*/}}