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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.