选择控件不从双向绑定中取值

时间:2021-04-03 01:53:43

标签: angular angular7

我有以下选择控件:

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

我正在对名为 available 的属性使用双向绑定。我想要的是让用户能够设置可用/不可用状态,后端方法将调用 API,如果失败,它将显示错误消息并将选择控件设置回其先前状态。

为了测试这个,我做了以下组件:

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

堆栈闪电战:https://stackblitz.com/edit/angular7-playground-sapjc8?file=src/app/app.component.ts

我期望发生的是,用户选择可用,然后立即将其设置回不可用,但发生的情况是设置 available 属性不会更改下拉列表。

我对角度绑定有什么误解?

1 个答案:

答案 0 :(得分:1)

这样做的原因是available的值恰好在handleChange中发生了变化,但是在change detection循环之后,这足以让您使用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)
}
相关问题