Search code examples
angularangular-ngmodelchange

Angular 2+ (ngModelChange) on input on itself


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.


Solution

  • 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;
        })
      }