Angular7,异步加载选项时,Select指令未选择选项

时间:2019-02-04 15:46:31

标签: angular asynchronous select

我有一个选择,其选项是通过http请求生成的。 当我得到答案并用* ng设置options标记时,第一个结果显示为在表单中选择的状态,但是在查看ngModel时,它们没有选择任何值

html

<select class="form-control" [(ngModel)]="filter.account">
  <option *ngFor="let account of accounts">{{account.name}}</option>
</select>

ts

ngOnInit() {
    this.filter = new AccountsCallLogFilter();
    this._acs.accounts().subscribe(
      val => {
        this.accounts = val;
        // this.filter.account = this.accounts[0].name; // <-- that works
      }
    );
  }

this.filter是此类的类

export class AccountsCallLogFilter {
    public "account": string
    public "dateFrom": string
    public "dateTo": string
}  

响应示例

[{ "accountId": "123456", "name": "Account1", "count": 2990 },
 { "accountId": "654321", "name": "Account2", "count": 5789 }]

我希望收到答案后,无需进行

之类的操作即可更新ngModel
this._acs.accounts().subscribe(
      val => {
        this.accounts = val;
        this.filter.account = this.accounts[0].name;
  }
);

当我手动更改选项时,值正确更新,问题仅在加载时

1 个答案:

答案 0 :(得分:0)

您没有提供选项的值,因此select不知道如何绑定它。试试这个:

<select class="form-control" [(ngModel)]="filter.account">
  <option *ngFor="let account of accounts" [value]="account.accountId">{{account.name}}</option>
</select>