0

In my project I have an input type="number" where the user should enter a number between 1(always) and another number. I want to restrict the UI input element, is such way that only numbers in that range can be entered. My code so far:

.html:

<p>Allowed values are 1 - {{max}}</p>
<input type="number" (input)="input($event)" />

.ts:

export class AppComponent {
  readonly max = 5;

  input(event: Event) {
    const inputElem = event.target as HTMLInputElement;
    if (+inputElem.value < 1) {
      inputElem.value = '1';
    } else if (+inputElem.value > this.max) {
      inputElem.value = this.max.toString();
    }
  }
}

Stackblitz here

The code works as I wish but I wonder if there is an Angular way of doing this, with [(ngModel)] or [ngModel] and (ngModelChange). I tried some things, but with no success.

cpper
  • 142
  • 2
  • 13

1 Answers1

1

it's very similar to this another SO

  readonly max = 5;
  mynumber = 2;
  validateInput(e: any, input: any = null) {
    let value = +e;
    if (value < 1) value = 1;
    if (value > this.max) value = this.max;
    this.mynumber = value;
    if (input.value != value) {
      const start = input.selectionStart ? input.selectionStart - 1 : -1;
      input.value = value;
      if (start>=0) input.selectionStart = input.selectionEnd = start;
    }
  }

<input type="number" #input [ngModel]="mynumber" 
     (ngModelChange)="validateInput($event,input)" />

see stackblitz

Eliseo
  • 50,109
  • 4
  • 29
  • 67