1

Input should not accept a number with more than N decimal places. N is defined as Input.

For example, if N=3 and the user want to enter 123.3456. He should only be allowed to enter 123.345.

I would like to ahieve something like this:

<input type="number" [(ngModel)]="value" nDecimalsInput [decimals]="2">

Via directive or whatever else...

  • https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field/54462816#54462816 – Eliseo Nov 07 '19 at 08:06

3 Answers3

0

Input mask will do. You may try a lib from npm or create the directive yourself.

In you case the lib is used like this:

<input type="number" [(ngModel)]="value" mask="0*.00">
Anton Rusak
  • 882
  • 4
  • 18
0

You can do a simple function on (keydown)="maxLength()"

maxLength() {
if (N && this.myFormControl.value.toString().split('.')[1].length === N) {
      return false;
    }
}
Ivan Mihaylov
  • 434
  • 2
  • 9
  • Thanks, but this.myFormControl.value is not updated at the keydown moment. It still didn't change value (keydown is triggered before value change) – Djordje Miladinovic Nov 07 '19 at 08:53
  • @DjordjeMiladinovic, yes and this is the expected and desired behavior. You want to be checking if you have reached the limit of numbers before inputting a new one. So if your N = 3 and your number is 1.222 after entering the next digit the maxLength function will check the number meaning 1.222 and see that the limit is reached and not add another one by returning 'false'. – Ivan Mihaylov Nov 08 '19 at 11:22
0

So you could do like this to override or hook to an event (like change or key up):

parseFloat($(this).val()).toFixed(3)

Or use a mask like: https://github.com/assisrafael/angular-input-masks and do

<input type="text" name="field" ng-model="number" ui-number-mask="3">
Jason Hughes
  • 748
  • 6
  • 18