You can create a custom currency pipe by implementing the PipeTransform interface and defining the transform method. This allows you to format numbers as currency according to your requirements.
Steps to Create a Custom Currency Pipe:
Generate the Pipe:
Use the Angular CLI to generate a pipe:
bash
ng generate pipe currency
Implement the Pipe:
In the generated pipe file (e.g., currency.pipe.ts), define the transformation logic.
Example: Custom Currency Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'customCurrency' })
export class CustomCurrencyPipe implements PipeTransform {
transform(
value: number,
currencyCode: string = 'USD',
display: 'symbol' | 'code' | 'name' = 'symbol',
digitsInfo: string = '1.2-2'
): string {
if (isNaN(value)) return '';
// Format the number as currency
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currencyCode,
currencyDisplay: display,
minimumFractionDigits: parseInt(digitsInfo.split('.')[1].split('-')[0]),
maximumFractionDigits: parseInt(digitsInfo.split('.')[1].split('-')[1])
}).format(value);
}
}
Usage in Template:
<p>{{ 1234.56 | customCurrency:'EUR':'symbol':'1.2-2' }}</p>
<!-- Output: €1,234.56 -->