首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular5 select型号

Angular5 select型号
EN

Stack Overflow用户
提问于 2018-02-12 17:51:29
回答 1查看 79关注 0票数 2

我有一个绑定到客户数组的Angular5 <select>。如下所示:

代码语言:javascript
复制
<select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x.id">{{x.name}}</option>
</select>

在事件函数中,我以‘setCustomer’的形式获得了一个客户的id。

属性record.customer_id是number类型,而不是object类型。有没有办法在setCustomer方法中获取整个customer实体,同时保留到record.customer_id的绑定?

我在Angular docu上找到了一种[compareWith]的方法,所以我尝试了:

代码语言:javascript
复制
<select class="form-control" [compareWith]="compareCustomer"  [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>

代码语言:javascript
复制
compareCustomer(c1: customer, c2: number) : boolean {
   if (c1 == null || c1 == undefined) {
     return false;
   }

   if (c1.id == c2) {

     return true;
   }

   return false;
}

不起作用。当我选择任何选项时,setCustomer将被执行,record.customer_id将获得选定的id。但是,在select失去焦点后,选定的选项将重置为空白。

有一个我想要避免的变通方法(在customers数组中迭代并通过id手动匹配):

代码语言:javascript
复制
 setCustomer(event) {

    this.record.customer_id = Number.parseInt(event);

    customers.forEach(c => {

       if (c.id === this.record.customer_id) {

           // some logic with selected customer


       }
    });
}

有什么建议吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-12 17:57:43

不绑定customer_id,而是绑定整个对象:

代码语言:javascript
复制
<select class="form-control" [ngModel]="record" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48743552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档