简体   繁体   English

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

[英]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.

相关问题 Angular7在一个选择中使用选择的选项来设置另一个选择中的选项 - Angular7 Use selected option in a select to set the options in another select 离子/角度 - Select 选项未标记,选项从 API 加载 - Ionic/Angular - Select option is not marked, options loaded from API Angular7 中的 Select2:在 select 标记中混合呈现选项的 styles - Select2 in Angular7: Mix styles of rendered options in a select tag 用远程数据填充angular7 select选项的正确方法? - correct way to populate angular7 select options with remote data? 当从 Angular 中的 API 获取选项时,在选择的对象中设置选项 - Set the option in a select of objects when the options are fetched from an API in Angular Select 不能在 Angular7 中使用 Materialise 渲染 - Select not render in Angular7 with Materialize 如何在 CodePen 上向 Angular7 应用程序添加指令 - How to add Directive to Angular7 app on CodePen 选择选项时角度4选择元素行为的问题 - An issue with angular 4 select element behavior on selecting an option 在 mat-select 中选择选项时,没有 output - When selecting the options in mat-select there is no output 显示和隐藏跨度<option>在 Angular7 - show and hide span in <option> in Angular7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM