Angular 2 - How to use build-in pipe inside custom pipe

Vijay Malik picture Vijay Malik · Feb 15, 2017 · Viewed 9.3k times · Source

I want to make a custom currency pipe using the built-in currency pipe. The way I want to use is {{ anyNumber | customCurrency }}. Then inside my customCurrency pipe, I want to use built-in currency pipe. I can decide the parameters to currency pipe based on some logic and don't want to specify locale and other parameters everywhere like {{anyNumber | currency:'USD':false:'1:0-0'}}.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customCurrency'
})
export class CustomCurrencyPipe implements PipeTransform {

  transform(value: any, args?: any): any {
      const defaultLocale = 'USD';
      const showSymbol = false;

      ......some logic here......      

      //HOW TO USE CURRENCY PIPE HERE?

 }

}

Answer

akos.bordas picture akos.bordas · Feb 15, 2017

You should inject the built-in pipe into your custom pipe than you can call it's transform method with your default values

@Pipe({
  name: 'customCurrency'
})
export class CustomCurrencyPipe implements PipeTransform {

  constructor(public currencyPipe: CurrencyPipe) {
  }

  transform(value: any, args?: any): any {
      const currencyCode = 'USD';
      const showSymbol = false;
      return currencyPipe.transform(value, currencyCode, showSymbol);
 }

}