[Fixed] Select control not taking value from two way binding

Issue

I have the following select control:

<select id="my-select" [(ngModel)]="available" (change)="handleChange($event)">
    <option value="true">Available</option>
    <option value="false">Unavailable</option>
  </select>

I am using a two way binding to a property called available. What I want is for the user to be able to set status available/unavailable, a backend method will make a call to the API and if it fails it will display an error message and set the select control back to it’s previous state.

To test this I did the following component:

import { TextAttribute } from "@angular/compiler/src/render3/r3_ast";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  available: boolean;
  ngOnInit(): void {
    this.available = false;
  }

  async handleChange(event: Event) {
    // ... some process to set status
    //oops error happened setting status, lets set it back
    this.available = false;
    console.log(event);
  }
}

Stack blitz: https://stackblitz.com/edit/angular7-playground-sapjc8?file=src/app/app.component.ts

What I expect to happen is that user select available and then it instantly gets set back to unavailable but what happens is setting available property doesn’t change the drop down.

What am I mis-understanding about angular bindings?

Solution

The reason for this is that exactly the value of available changes in the handleChange, but after change detection cycle, that’s enough for you to use setTimeout

async handleChange(event: Event) {
  // ... some process to set status
  //oops error happened setting status, lets set it back
  setTimeout(() => {
    this.available = false;
    console.log(event);
  }, 0)
}

Leave a Reply

(*) Required, Your email will not be published