Set default parameters for angular pipes
Most of angular pipes use existing methods to return their transform value , for example if you take a look at the currency pipe you'll see that it uses two method to return the string value of the formatted numer to currency , formatCurrency and getCurrencySymbol and they are available in angular common module so we can use them to build our own version of the currency pipe without the need of inheritance or something like that , simply the currency pipe return the return value of formatCurrency function and call it with the params passed to the pipe and uses getCurrencySymbol to get the symbol of a specified currency code
so now we can build our own version with default values we specify and here it is
import { Pipe, PipeTransform } from '@angular/core';
import { formatCurrency, getCurrencySymbol } from '@angular/common';
@Pipe({
name: 'mycurrency',
})
export class MycurrencyPipe implements PipeTransform {
transform(
value: number,
currencyCode: string = 'EUR',
display:
| 'code'
| 'symbol'
| 'symbol-narrow'
| string
| boolean = 'symbol',
digitsInfo: string = '0.2-2',
locale: string = 'en-US',
): string | null {
return formatCurrency(
value,
locale,
getCurrencySymbol(currencyCode, 'wide'),
currencyCode,
digitsInfo,
);
}
}
Now its working perfect
Note here I am using en-US as locale if you need to use other locale such as de you need to import it and register,
more info
angular pipes
CurrencyPipe
formatCurrency
getCurrencySymnol
angular common
Simple as you inject DEFAULT_CURRENCY_CODE to your providers
import { DEFAULT_CURRENCY_CODE, } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
registerLocaleData(localeDe, localeDeExtra);
@NgModule({
providers: [
{
provide: LOCALE_ID,
useValue: 'de'
},
{
provide: DEFAULT_CURRENCY_CODE,
useValue: 'EUR'
}
]
})
Since I believe it's not possible I've extended angular's CurrencyPipe class with below class, using default parameters in transform
@Pipe({
name: 'deCurrency'
})
export class DeCurrencyPipe extends CurrencyPipe implements PipeTransform {
transform(value: number, currencyCode: string = 'EUR', display: 'code' | 'symbol' | 'symbol-narrow' | string | boolean = 'symbol', digitsInfo: string = '0.2-2', locale: string = 'de'): string | null {
return super.transform(value, currencyCode, display, digitsInfo, locale);
}
}
I'm still very open to suggestions on setting default values without writing my own...