I am working on a little project with Angular, the input from a form doesn´t let me introduce a decimal value, like 23.5. I don´t know if something is wrong, here is the code:
<div class="form-group" *ngIf="bolivaresVisible" [ngClass]="{'has-error': cuenta.get('bolivares')?.invalid && cuenta.get('bolivares')?.touched}">
<label for="bolivares{{i}}">{{ cuenta.get('currency')?.value === 'bolivares' ? 'Bolívares' : 'Pesos' }} <span class="required">*</span></label>
<div class="input-button-group">
<input id="bolivares{{i}}"
type="text"
inputmode="decimal"
[formControlName]="cuenta.get('currency')?.value === 'bolivares' ? 'bolivares' : 'pesos'"
placeholder="Ingrese cantidad"
(input)="onBolivaresOrPesosInput($event, i)">
<button mat-icon-button type="button" (click)="toggleCurrency(i)">
<mat-icon>swap_horiz</mat-icon>
</button>
</div>
</div>
TypeScript
onBolivaresOrPesosInput(event: Event, index: number): void {
const inputElement = event.target as HTMLInputElement;
let inputValue = inputElement.value;
// Permitir solo un punto decimal y dígitos
inputValue = inputValue.replace(/[^\d.]/g, '');
const parts = inputValue.split('.');
if (parts.length > 2) {
parts[1] = parts.slice(1).join('');
inputValue = parts.slice(0, 2).join('.');
}
inputElement.value = inputValue;
const numericValue = parseFloat(inputValue);
const control = this.cuentasDestinatarioArray.controls[index];
if (!isNaN(numericValue)) {
if (control.get('currency')?.value === 'bolivares') {
control.get('bolivares')?.setValue(numericValue, { emitEvent: false });
} else if (control.get('currency')?.value === 'pesos') {
control.get('pesos')?.setValue(numericValue, { emitEvent: false });
}
} else {
// Si no es un número válido, establecer el valor como null o ''
if (control.get('currency')?.value === 'bolivares') {
control.get('bolivares')?.setValue(null, { emitEvent: false });
} else if (control.get('currency')?.value === 'pesos') {
control.get('pesos')?.setValue(null, { emitEvent: false });
}
}
this.updateLabelsBasedOnInputs();
}
I have an
onBolivaresOrPesosInputmethod that handles the input event. It attempts to format the input to allow only digits and one decimal point.The method updates the form control value based on the currency type (bolivares or pesos).
In the HTML, I'm using a form control with
inputmode="decimal"and binding it to the appropriate form control name based on the selected currency.There's also a button to toggle between currencies.
Despite these implementations, users are unable to input decimal values as intended. The input seems to be rejected or not properly handled with decimal points.
I've tried using regular expressions to clean the input and allow for one decimal point, but it's not working as expected. Here's a snippet of the relevant code:
Any insights on why decimal inputs might not be working and how to resolve this issue would be greatly appreciated.