angular 2 - 将对象绑定到下拉列表并根据事件选择值

时间:2016-08-23 16:01:10

标签: angular typescript binding

我创建了一个下拉列表,供应商将其绑定为对象。

<select class="form-control" name="supplier" required
                            [(ngModel)]="selectedSupplier" #supplier="ngModel">
    <option *ngFor="let supplier of suppliers" [ngValue]="supplier">{{supplier.name}}</option>
</select>

我在此下拉列表的顶部有一个网格,我在其中选择值并将其添加到表格网格中。

<tr *ngFor="let relationship of relationships">
     <td>{{relationship.supplierName}}</td>
     <td>{{relationship.businessArea}}</td>
     <td>{{relationship.contacts[0].name}}</td>
     <td><a href="javascript:void(0)" (click)="onEdit(relationship)">Edit</a></td>
</tr>

关系有supplierName和supplierId。我试图选择下拉onEdit事件的值,但我似乎无法使其工作。以下是我到目前为止的尝试。

首次尝试:

private selectedSupplier: any;
private onEdit(relationship: Relationship): void {
        this.selectedSupplier = {id: relationship.supplierId, name: relationship.supplierName};
    }

第二次尝试:

private selectedSupplier: Dictionary;
private onEdit(relationship: Relationship): void {
        this.selectedSupplier = new Dictionary(relationship.supplierId, relationship.supplierName);
    }
export class Dictionary{
       constructor(public id:number, public name:string){}
}

第三次尝试:

private selectedSupplier: any;
private onEdit(relationship: Relationship): void {
        this.selectedSupplier.id = relationship.supplierId;
     // this.selectedSupplier.id = 2;
    }

任何想法我怎么能实现这一点?下面是截图...

enter image description here

我也创造了一个简单的plunker ... https://plnkr.co/edit/Z11peGQmzYuwY6l6U9Ri?p=preview

2 个答案:

答案 0 :(得分:3)

似乎Angular2使用对象引用而不是属性,因此如果你这样做,它将起作用:

private onEdit(relationship: Relationship): void {
  this.selectedSupplier = this.suppliers.find(supplier => supplier.id === relationship.supplierId);
}

您需要从select中传递完全相同的对象。

答案 1 :(得分:1)

问题是您将选项值设置为Object,因此当您设置所选关系值时,您需要设置相同的确切对象(不是它的类似表示),以便ngModel准确知道哪个选项设置为选中。例如,你的plunker的这个叉:https://plnkr.co/edit/VroxlTMkV30HbqB1DvYq

onEdit(relationship){
    let name:string = relationship.supplierName;
    let found:boolean = false;
    for (let i = 0; i < this.suppliers.length && !found; i++) {
      let supplier:any = this.suppliers[i];
      if (supplier.name === name) {
        found = true;
        this.selectedSupplier = supplier
      }
    }
    /* if (!found) what to do? */
  }
}

使用关系的名称,搜索供应商列表,然后将selectedSupplier设置为具有正确名称的供应商。

但是,我并不喜欢将Options的值设置为Object。如果我要设计它,我宁愿使用ID作为Option值,它会使代码更容易。