Home > front end >  Angular - prevent entering number outside of range in input type="number"
Angular - prevent entering number outside of range in input type="number"

Time:10-25

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.

CodePudding user response:

you can combine (input) with [(ngmode)] something like ↓

<input (input)="KeyPress($event)" [(ngModel)]="value" />

on ts ↓

KeyPress(event: any) {
    console.log(this.value);
    let newValue = event.target.value;
    let regExp = new RegExp('^[1-5] $');

    if (!regExp.test(newValue)) {
      event.target.value = newValue.slice(0, -1);
    }
  }

here the sample

for more explanation you can check ↓

(change) vs (ngModelChange) in angular

Angular (change) event not firing on all changes

CodePudding user response:

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

  • Related