角度2-将对象绑定到下拉列表并根据事件选择值 [英] angular 2 - bind object to dropdown and select value based on an event

查看:90
本文介绍了角度2-将对象绑定到下拉列表并根据事件选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个下拉菜单,其中将绑定了供应商的对象作为对象.

I have created a dropdown which has suppliers bound to it as an object.

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

在此下拉菜单的顶部有一个网格,我可以在其中选择值并将其添加到表格网格中.

I have a grid on top of this dropdown where i select the values and add it in the table grid.

<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事件的值,但是我似乎无法使其工作.下面是我到目前为止的尝试.

relationship has supplierName as well as supplierId. I am trying to select the value of the dropdown onEdit event but i can't seem to make it work. below are my attempts so far.

首次尝试:

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;
    }

我知道该如何实现?下面是屏幕截图...

any idea how can i acheive that? below is the screenshot...

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

I have created a simple plunker as well... https://plnkr.co/edit/Z11peGQmzYuwY6l6U9Ri?p=preview

推荐答案

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

It seems Angular2 uses objects reference, instead of properties, so if you do this, it will work:

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

您需要传递与选择对象完全相同的对象.

You need to pass the exact same object from the select.

这篇关于角度2-将对象绑定到下拉列表并根据事件选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆