Number formatting as-you-type in an input field in

2019-06-23 23:36发布

问题:

With pipes like

<input....
    [ngModel]="whatever | myCurrencyPipe"
    (ngModelChange)="whatever = $event"
    type="text"
    name="myCurreny"
    ...

you can format an existing value. Scarcely you want to overwrite the value, you have problems. And with the solution above, the double binding has been abrogated.

There are plenty of jQuery-Libraries but I am looking for native angular2 solutions.

Can someone help me?

回答1:

  1. Extend NgModel directive. Overwrite function viewToModelUpdate(value) called after every input change and setting the model value.
  2. Replace NgModel to your implementation (providers[] in module)
  3. Read regexp or filter or formatter from specified attribute, directly on input like: < input filter="currency" />

Working example you can find here: http://stacktrase.com/2017/07/14/angularjs4-restrict-input-text-by-extending-ngmodel/