Angular 9 : html select does respect value in model after click

Viewed 284

I am implementing a component where in a user is asked to confirm his choice when he selects a value from an HTML select. If the user selects no, i want to revert to the older value. The reverting works and the model gets updated but the select view does not show the right value. Instead it shows the value user clicked on. i have minimal working example here : https://stackblitz.com/edit/angular-ivy-8cybe9

I tried using changedetection as well but that too doesnt help.

1 Answers

The select element displays the value selected in the list, which is the normal behavior of the browser. And since the model value has not changed, Angular does not see any reason to update the element. To trigger such an update and put back the previous value, we must force Angular to detect a change, even when that change was cancelled afterwards. Here is one way to do it:

  1. Set the model property to the new value
  2. Call ChangeDetectorRef.detectChanges() to force change detection
  3. Restore the previous value in the model property
  4. Optionally: call ChangeDetectorRef.detectChanges() again to prevent flicker
updateMetric(currentVal, prevVal) {
  this.currentVal = currentVal;
  this.preVal = prevVal;
  this.model.rating = currentVal;             // <-- set new value
  if (window.confirm("Proceed?")) {
    this.currentVal = currentVal;
  } else {
    this.changeDetectorRef.detectChanges();   // <-- force change detection
    this.model.rating = prevVal;              // <-- restore previous value
    this.currentVal = prevVal;
    this.changeDetectorRef.detectChanges();   // <-- prevent flicker
  }
}

See this stackblitz for a demo.

Related