i've only been learning Angular for a short time and I'm facing a problem. I have built a form using reactive forms. The user can enter an amount of money in an input field. When he leave the field, I would like the value to be automatically formatted into German notation. (e.g. 87.998,00) I don't need the euro symbol.
So far I haven't been able to find a solution to solve this with reactive forms via a pipe. Is it worth continuing to search or do I have to solve this using a classic Javascript function?
So far I've only managed to include the two decimal places.
validateCurrency(event: any){
let t = event.target.value;
event.target.value =
t.indexOf(',')>= 0
? t.substr(0, t.indexOf(',')) + t.substr(t.indexOf(','), 2)
: t;
}
Edit:
For an Example, here is my Form:
<form [formGroup]="decimalForm">
<input type="text" #userNumber (blur)="changeNumber()" formControlName="userNumber">
And the .ts of the component
import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrl: './forms.component.scss'
})
export class FormsComponent {
public decimalForm: FormGroup = new FormGroup({
userNumber: new FormControl('Test')
})
@ViewChild("userNumber") userNumber!: ElementRef;
changeNumber() {
}
}
In the function changeNumer() I need the code, to change the value after the user leave the input.
Typical if you want to "formatting a number" in (blur) you use a directive
And use like
NOTE: Don't forget register your locale using
registerLocaleDataa stackbtliz
Update
We can change the parse function to allow the ","Generally, if we want to store in a dbs, the numbers should be in "standard format" (in en-US). But, we want to use the decimal separator in our locale.
So, we can declare a variable
and in constructor of the directive get the value
Now we need change a bit the functions parse and onFocus
Just corrected in stackblitz