I need that from the input when the user enters the price , the currencyPipe transforms it automatically, for example, that it allows writing 1500.25 or 1500 without decimals. The way I have done it is using the currencyPipe in the valueChanges of the formControl price does not work because if the user wanted to write 1500 it automatically becomes 1,500. and if you also wanted to write 1500.25 it transforms it to 150.025.
component.ts
import { CurrencyPipe } from '@angular/common';
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+/, ''), '', '', '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)]],
author: ['', [Validators.required]],
category: ['', [Validators.required]],
editorial: ['', [Validators.required]],
description: ['', [Validators.required, Validators.maxLength(2500)]],
quantity: ['', [Validators.required]],
price: ['', [Validators.required]],
image: [''],
state: [true]
});
}
component.html (I only show the price input, which is the one that matters to save code)
<form [formGroup]="form">
<div class="form-group col-md-6 mb-3">
<input
class="form-control"
formControlName="price"
step="0.01"
[(ngModel)]="book.price"
placeholder="Precio $"
/>
<div *ngIf="form.get('price').errors && form.get('price').dirty">
<p
class="text-center mt-1"
*ngIf="form.get('price').hasError('required')"
>
<small class="text-danger">Este campo es obligatorio!</small>
</p>
</div>
</div>
</form>
You can easily achieve this with the library
ngx-mask
It basically converts a string to the desired format and returns a clean string. Note that the input must be
type="text"
for it to work.Here is a working example