angularangular11backspacetwo-way-bindingnumeric-input

Angular 11 two way binding for a numeric field: backspace not working as expected and giving junk values whenever pressed


I am working with Angular 11 and came across two way binding for quantity field which is an input field of the type number. Problem arrives when I try to use backspace for the quantity field input. It gives junk values which are then displayed with the correct value.

.html file

<button class="btn btn-outline-primary btn-lg" (click)="addProductToCart(product,1)">
<i class="fa-solid fa-plus"></i></button>
<input type="number" [ngModel]="product.quantity" (ngModelChange)="addProductToCart(product,$event)" id="prod-qty">
<button class="btn btn-outline-primary btn-lg" (click)="addProductToCart(product,-1)">
<i class="fa-solid fa-minus"></i></button>

.ts file

addProductToCart(pr: any, q: any){
    pr.quantity=pr.quantity+Number(q);
 }

Is there any workaround for this issue?? Please do let me know


Solution

  • You need to use two ways binding: [(ngModel)]="binding".

    Your input should be:

    <input type="number" [(ngModel)]="product.quantity" id="prod-qty">