When pasting the same value into Input field, on second time pasting two-way data binding doesn't work

Issue

I have the following input tag:

<input type="number" [ngModel]="position" (ngModelChange)="onChangePosition($event)" />

onChangePosition function mainly checks the length of the input value, if the length is more than 3 it cuts and leaves only 3 numbers.
When I paste long numbers like 12345, the first time it cuts and sets 123 to position property and that is reflected on the view.
But when pasting the same value over old one on second time, position changes as before but not reflected on the view.

You can see this behavior in
DEMO

Copy value 12345 and paste it into the field, you will see 123. Correct result.
Then paste value into field again, you will see that position is changed but inside input field it stays as it is. Unwanted result.

Appreciate any suggestion.

Solution

You can leverage the gap between what your input and what is in ngModel with (input) event:

<input type="number" #myPosition
       [ngModel]="position"
       (input)="myPosition.value = position"
       (ngModelChange)="onChangePosition($event)" />

Here I used the template variable and its value

DEMO

Answered By – Vega

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.