Angular 2+ (ngModelChange) on input on itself

1k Views Asked by At

I have number input field and I want to restrict it so max value will be 100. So When user types number by number I want it to be restricted in real time. For this I'm using (ngModelChange).

Example:

  • User types 1 its OK,
  • User types again 1, its OK,
  • User types 1 again it will automatically replace 111 with 100, and its OK
  • User types 1 again it should be automatically replaced with 100. but it stays 1001 and it will continue adding numbers regarding ngModelChange restriction.

Here is html code:

<!-- NOT WORKING -->
<input type="number"
       class="form-control"
       maxlength="3"
       [(ngModel)]="period"
       (ngModelChange)="onValueChange()"
       id="period" placeholder="0" min="0"
       max="100" step="1" name="period">

<!-- WORKING -->
<p>{{period}}</p>

It's controller:

  public period: number;

  onValueChange() {
     if (this.period > 100) this.period = 100;
  }

This will update period but only once. If I continue to type more numbers it wont update the input field. Also maxlength="3" is not working

I tried the same concept but on paragraph and it is working. Probably the problem is only on input field.

3

There are 3 best solutions below

0
On BEST ANSWER

Since You updating the model value inside ngModelChange the model value is out of sync with view value. try updating the model value asynchronusly inside settimeout.

onValueChange() {
    setTimeout(()=>{
      if (this.period > 100) this.period = 100;
    })
  }
1
On

Use FormControl and validators instead:

<input class="form-control" 
        type="number" 
        min="0" 
        max="100" 
        placeholder="0" 
        [(ngModel)]="period" 
        name="period" 
        [formControl]="period">

this.period= new FormControl("", [Validators.max(100)]);
3
On

try to use instead (input) of (ngModelChange) :

(input)="onValueChange($event)"

in your ts code will be :

onValueChange(event): void {
  console.log(event);
  let p = event.target.value;
  if (p > 100) this.period = 100;
}