Changes to NgModel on input not updating view

On your second edit, the content of the input element is not updated because Angular has not detected any change (option.value was 5, and it is still 5). Here are two methods to force the refresh of the element.


Method 1 - Replace the option item in the array

You can force the field to update by replacing the option in the array with a cloned copy, as shown in this stackblitz:

<div *ngFor="let option of options; let i=index">
  <input [ngModel]="option.value" (change)="onChangeValue($event.target.value, i)" type="text" >
</div>
onChangeValue(valueString: string, index: number) {
  var value: number = parseInt(valueString);
  if (value > 5) {
    value = 5;
  }
  this.options[index] = this.options[index].cloneWithValue(value);
}

export class OptionViewModel {
  public optionId: number;
  public description: string;
  public pollId: number;
  public value?: number;

  public cloneWithValue(value: number): OptionViewModel {
    let dest = new OptionViewModel();
    dest.optionId = this.optionId;
    dest.description = this.description;
    dest.pollId = this.pollId;
    dest.value = value;
    return dest;
  }
}

Method 2 - Use an additional field in the trackBy function

An alternative solution is to add an additional field to OptionViewModel (e.g. lastModified) and to use it in a trackBy method of the ngFor directive (see this stackblitz):

<div *ngFor="let option of options; trackBy: trackByFn">
  <input [ngModel]="option.value" (change)="onChangeValue($event.target.value, option)" type="text">
</div>
onChangeValue(valueString: string, option: OptionViewModel) {
  var value: number = parseInt(valueString);
  if (value > 5) {
    value = 5;
  }
  option.value = value;
  option.lastModified = Date.now();
}

trackByFn(index: number, option: OptionViewModel) {
  return `${index}___${option.lastModified}`;
}
export class OptionViewModel {
  public optionId: number;
  public description: string;
  public pollId: number;
  public value?: number;
  public lastModified: number = 0;
}

Hi try to change ng model two way binding ,like that

    <div *ngFor="let option of options">
        <input type="text" [(ngModel)]="option.value"  #ctrl="ngModel"
 (change)="onChangeValue($event.target.value, option)">
    </div>

Tags:

Angular