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();
}
}
}
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.