In my reactive form I have an input for the price, as the user writes the price, it takes the dollar format by default, but I need it to take the Argentine peso format by default.
COMPONENT.TS
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';
form: FormGroup;
constructor(
private currencyPipe: CurrencyPipe,
private formBuilder: FormBuilder
) {
this.buildForm();
// cuando escribe el precio
this.form.valueChanges.subscribe(formulario => {
if(formulario.price){
this.form.patchValue({
price: this.currencyPipe.transform(formulario.price.replace(/\D/g, '').replace(/^0+/, ''), 'USD', 'symbol', '1.0-0')
}, {emitEvent: false});
}
})
}
buildForm() {
this.form = this.formBuilder.group({
// name: ['', [Validators.required, Validators.maxLength(50)]],
// year: ['', [Validators.required, Validators.min(1500),Validators.max(this.year)]],
price: ['', [Validators.required]],
});
}
Here component.html (I only show the price input to save code).
<form [formGroup]="form">
<label>Precio</label>
<input type="text" formControlName="price" placeholder="$">
</form>
It would be interesting if you could mention which version of Angular you are working with. However, I will assume that you are working with version 11 (latest).
As the documentation indicates, you can use formatCurrency() , since you're implementing it from code, not the template.
Structure of the overload (according to documentation):
It is worth mentioning that it
currencyCode
receives ISO-4217 code of the currency that, in the case of Argentina, is ARS .Example:
In this case, we assume it
locale
isen-US
, but you can implement another one having the proper i18n configuration.The third parameter,
'ARS '
, is the prefix of the text (you can put it as'$'
).The fourth parameter
'ARS'
is the ISO-4217 codeThe last parameter is the template format for the decimal. Its structure is:
MaximumNumberOfIntegers.MinimumDigitsOfFraction/decimals-MaximumDigitsOfFraction/decimals
That is, according to the previous example (
4.2-2
):4
: maximum number of integers2
: minimum2
number of decimal places : maximum number of decimal placesExpected result according to example:
Printed as:
AR$1,521.80
I leave these examples for reference, as there is more than one way to implement this functionality.