NgModel not always updating text input

447 Views Asked by At

I'm working on a scenario where I want the ngModel to get update based on certain conditions

Template:

<mat-form-field>
    <mat-label>val:</mat-label>
    <input matInput [(ngModel)]="someVal" (ngModelChange)="onChange($event)">
</mat-form-field>

Component:

someVal: number = 10;
onChange(val: number):void {
  if(val > 10){
    this.someVal = 0;
  }
}

On the first attempt to change the value to something greater than 10, the view updates. But subsequent changes don't. What causes this behavior and how does one work around this?

3

There are 3 best solutions below

1
On

Do not do this ...

[(ngModel)]="someVal" (ngModelChange)="onChange($event)"

do this ...

[ngModel]="someVal" (ngModelChange)="onChange($event)"

onChange(val: number):void {
  if(val > 10) val = 0;
  this.someVal = val;
}
0
On

Add name property.

<input matInput name="val" [(ngModel)]="someVal" (ngModelChange)="onChange($event)">
0
On

As a workaround I did this for now.

private _cdRef: ChangeDetectorRef

public someVal: number = 10;
onChange(val: number):void {
  if(val > 10){
    this.someVal = null;
    this._cdRef.detectChanges();
    this.someVal = 0;
  }
}