Help me een aangepaste Angular-pijp implementeren voor valutaopmaak.
description
Gebruikers krijgen de mogelijkheid om nummers duidelijk en gestandaardiseerd weer te geven in valuta-indeling, wat de algehele gebruikerservaring en gegevenspresentatie in hun Angular-toepassingen verbetert.
prompt
try_prompt
Leid me door het maken van een aangepaste Angular-pijp die nummers formatteert in een gespecificeerde valuta-indeling. Leg uit hoe je de pijp def ... more
generate_helper
...
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hieronder vind je een stapsgewijze gids om een aangepaste Angular-pijp te maken die nummers formatteert in de valuta-indeling USD.
### 1. Maak een nieuwe pijp aan
Gebruik Angular CLI om een nieuwe pijp te genereren:
```bash
ng generate pipe currencyFormat
```
### 2. Definieer de pijp (`currency-format.pipe.ts`)
Open het gegenereerde bestand en pas het als volgt aan:
```typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencyFormat'
})
export class CurrencyFormatPipe implements PipeTransform {
transform(value: number | string, currencySymbol: string = 'USD'): string {
if (value == null) {
return '';
}
// Converteer naar getal als het een string is
const numberValue = typeof value === 'string' ? parseFloat(value) : value;
if (isNaN(numberValue)) {
return '';
}
// Format de waarde met twee decimalen, scheidingstekens en valuta teken
const formattedNumber = numberValue.toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
// Als je alleen het bedrag wilt zonder het valuta-teken:
// const formattedNumber = numberValue.toLocaleString('en-US', {
// minimumFractionDigits: 2,
// maximumFractionDigits: 2
// });
// Voeg valuta teken toe als je dat wilt
// Bijvoorbeeld: '$' voor USD
// return `$${formattedNumber.replace('$', '').trim()}`;
return formattedNumber;
}
}
```
**Uitleg:**
- De pijp converteert input naar een getal.
- Het gebruikt `toLocaleString` met `en-US` om USD-formattering te verkrijgen.
- Je kunt de valuta-indicator aanpassen of verwijderen afhankelijk van je voorkeur.
### 3. Voeg de pijp toe aan je module
Zorg dat je de pijp declareert in je `app.module.ts` of een relevante module:
```typescript
import { CurrencyFormatPipe } from './currency-format.pipe';
@NgModule({
declarations: [
// andere componenten
CurrencyFormatPipe
],
// ...
})
export class AppModule { }
```
### 4. Gebruik de pijp in je componenten
In je HTML-templates:
```html
<p>{{ 1234.56 | currencyFormat }}</p>
```
Dit toont:
**$1,234.56**
Indien je de valuta-indicator wil aanpassen of toevoegen, kun je dat in de pijp zelf doen of de `transform`-functie verder uitbreiden.
---
### Samenvatting
- Maak een nieuwe pijp aan.
- Gebruik `toLocaleString('en-US', { style: 'currency', currency: 'USD' })` voor de juiste valuta-indeling.
- Voeg de pijp toe aan je module.
- Gebruik de pijp in je templates.
Wil je bijvoorbeeld geen valuta-teken maar alleen het nummer met een `$` ervoor, dan kun je dat aanpassen in de `transform`-functie zoals aangegeven.
provider: deepseek
model: deepseek-chat
Ik zal je stap voor stap begeleiden bij het maken van een aangepaste Angular-pijp voor valutaformattering, specifiek voor USD.
## Stap 1: Pijp genereren en definiëren
```bash
ng generate pipe currency-format
```
Of maak handmatig een bestand `currency-format.pipe.ts`:
```typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencyFormat'
})
export class CurrencyFormatPipe implements PipeTransform {
transform(
value: number | string,
currencyCode: string = 'USD',
display: 'symbol' | 'code' | 'name' = 'symbol',
digitsInfo: string = '1.2-2'
): string {
if (value == null || value === '') return '';
// Converteren naar number
const numericValue = typeof value === 'string' ? parseFloat(value) : value;
if (isNaN(numericValue)) return 'Ongeldig bedrag';
// Valuta-indeling toepassen
return this.formatCurrency(numericValue, currencyCode, display, digitsInfo);
}
private formatCurrency(
value: number,
currencyCode: string,
display: string,
digitsInfo: string
): string {
// Gebruik Angular's built-in currency pipe intern
const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
return formatted;
}
}
```
## Stap 2: Geavanceerde versie met meer opties
```typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencyFormat'
})
export class CurrencyFormatPipe implements PipeTransform {
private currencySymbols: { [key: string]: string } = {
'USD': '$',
'EUR': '€',
'GBP': '£',
'JPY': '¥',
'CAD': 'C$'
};
transform(
value: number | string,
currencyCode: string = 'USD',
display: 'symbol' | 'code' | 'name' | 'custom' = 'symbol',
digitsInfo: string = '1.2-2',
locale: string = 'en-US'
): string {
if (value == null || value === '') return '';
const numericValue = typeof value === 'string' ? parseFloat(value) : value;
if (isNaN(numericValue)) return 'Ongeldig bedrag';
return this.customFormat(numericValue, currencyCode, display, digitsInfo, locale);
}
private customFormat(
value: number,
currencyCode: string,
display: string,
digitsInfo: string,
locale: string
): string {
switch (display) {
case 'symbol':
return this.formatWithSymbol(value, currencyCode, locale);
case 'code':
return this.formatWithCode(value, currencyCode, locale);
case 'name':
return this.formatWithName(value, currencyCode, locale);
case 'custom':
return this.formatCustom(value, currencyCode);
default:
return this.formatWithSymbol(value, currencyCode, locale);
}
}
private formatWithSymbol(value: number, currencyCode: string, locale: string): string {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
}
private formatWithCode(value: number, currencyCode: string, locale: string): string {
const formatted = new Intl.NumberFormat(locale, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
return `${formatted} ${currencyCode}`;
}
private formatWithName(value: number, currencyCode: string, locale: string): string {
const formatted = new Intl.NumberFormat(locale, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
const currencyNames: { [key: string]: string } = {
'USD': 'US Dollar',
'EUR': 'Euro',
'GBP': 'Britse Pond'
};
return `${formatted} ${currencyNames[currencyCode] || currencyCode}`;
}
private formatCustom(value: number, currencyCode: string): string {
const symbol = this.currencySymbols[currencyCode] || currencyCode;
return `${symbol} ${value.toFixed(2)}`;
}
}
```
## Stap 3: Pijp registreren in module
Zorg dat de pijp is geregistreerd in je module:
```typescript
import { NgModule } from '@angular/core';
import { CurrencyFormatPipe } from './currency-format.pipe';
@NgModule({
declarations: [
CurrencyFormatPipe
],
exports: [
CurrencyFormatPipe
]
})
export class AppModule { }
```
## Stap 4: Gebruik in component templates
```html
<!-- Basis gebruik voor USD -->
<p>{{ 1234.56 | currencyFormat }}</p>
<!-- Resultaat: $1,234.56 -->
<!-- Expliciete valuta code -->
<p>{{ 1234.56 | currencyFormat:'USD' }}</p>
<!-- Verschillende display opties -->
<p>{{ 1234.56 | currencyFormat:'USD':'symbol' }}</p>
<!-- Resultaat: $1,234.56 -->
<p>{{ 1234.56 | currencyFormat:'USD':'code' }}</p>
<!-- Resultaat: 1,234.56 USD -->
<p>{{ 1234.56 | currencyFormat:'USD':'name' }}</p>
<!-- Resultaat: 1,234.56 US Dollar -->
<p>{{ 1234.56 | currencyFormat:'USD':'custom' }}</p>
<!-- Resultaat: $ 1234.56 -->
<!-- Met variabele uit component -->
<p>{{ bedrag | currencyFormat:'USD':'symbol' }}</p>
```
## Stap 5: Gebruik in component class
```typescript
import { Component } from '@angular/core';
import { CurrencyFormatPipe } from './currency-format.pipe';
@Component({
selector: 'app-example',
template: `
<div>
<p>{{ formattedAmount }}</p>
<p>{{ anotherFormattedAmount }}</p>
</div>
`
})
export class ExampleComponent {
bedrag = 9876.54;
constructor(private currencyPipe: CurrencyFormatPipe) {}
get formattedAmount(): string {
return this.currencyPipe.transform(this.bedrag, 'USD', 'symbol');
}
get anotherFormattedAmount(): string {
return this.currencyPipe.transform(123.45, 'USD', 'code');
}
}
```
## Belangrijkste kenmerken:
1. **Flexibele parameters**: Valutacode, display type en locale
2. **Foutafhandeling**: Controleert op ongeldige waarden
3. **Meerdere formaten**: Symbol, code, name en custom opties
4. **TypeScript ondersteuning**: Sterke typing voor betrouwbaarheid
5. **USD-specifiek**: Standaard ingesteld op USD met dollar symbool
Deze pijp geeft je volledige controle over hoe valuta wordt weergegeven in je Angular applicatie!

