[英]Angular7, Select directive not selecting option when options are loaded asynchronously
I have a select whose options are generated with an http request.我有一个选择,其选项是通过 http 请求生成的。 When I get the answer and I set the options tag with
*ngFor
the first result appears as selected in the form, however looking at the ngModel
they have no value selected当我得到答案并使用
*ngFor
设置选项标签时,第一个结果在表单中显示为选定的,但是查看ngModel
他们没有选择值
html html
<select class="form-control" [(ngModel)]="filter.account">
<option *ngFor="let account of accounts">{{account.name}}</option>
</select>
ts 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 is a class of this type this.filter 是这种类型的类
export class AccountsCallLogFilter {
public "account": string
public "dateFrom": string
public "dateTo": string
}
response example响应示例
[{ "accountId": "123456", "name": "Account1", "count": 2990 },
{ "accountId": "654321", "name": "Account2", "count": 5789 }]
I would like that when receiving the answer the ngModel will be updated without having to do something like我希望在收到答案时 ngModel 将被更新而无需执行类似的操作
this._acs.accounts().subscribe(
val => {
this.accounts = val;
this.filter.account = this.accounts[0].name;
}
);
when i change manually the option, value updates correctly, the problem is only at load当我手动更改选项时,值会正确更新,问题仅在加载时
You have not provided value for options so select has no clue how to bind it.您尚未为选项提供值,因此 select 不知道如何绑定它。 Try this:
尝试这个:
<select class="form-control" [(ngModel)]="filter.account">
<option *ngFor="let account of accounts" [value]="account.accountId">{{account.name}}</option>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.