Search code examples
angulardryangular-pipe

DRY in Angular pipes


I have a couple of amount variables which I want to format via currency pipe. This is the very simplified version of component's template:

<p>{{amount1 | currency : 'USD' : 'symbol' : '1.0-0'}}</p>
...
<p>{{amount2 | currency : 'USD' : 'symbol' : '1.0-0'}}</p>
...
<div>{{amount3 | currency : 'USD' : 'symbol' : '1.0-0'}}</div>
...
<h1>{{amount4 | currency : 'USD' : 'symbol' : '1.0-0'}}</h1>

How to achieve DRY in this example? Notice that the amount elements are not in the same level (i.e. couldn't be generated via *ngFor).

p.s. also it would be great to see the parametrized solution (in case of some currencies have another configs, like currencyCode, digitsInfo etc.)


Solution

  • You can extend the CurrencyPipe:

    import { Pipe } from '@angular/core';
    import { CurrencyPipe } from '@angular/common';
    
    @Pipe({
      name: 'usdCurrency'
    })
    export class UsdCurrencyPipe extends CurrencyPipe {
      transform(value: number, digitsInfo: string = "1.0-0"): any {
        return super.transform(value, "USD", "symbol", digitsInfo);  }
    }
    

    and apply that custom pipe in your template:

    <p>{{amount1 | usdCurrency }}</p>
    <p>{{amount2 | usdCurrency }}</p>
    <div>{{amount3 | usdCurrency }}</div>
    <h1>{{amount4 | usdCurrency : "1.2-2" }}</h1>
    

    In the example above, digitsInfo is available as an optional parameter. The other parameters could be made available if needed (currencyCode, display, locale).

    See this stackblitz for a demo.