Kamran Pervaiz Kamran Pervaiz - 3 months ago 43
TypeScript Question

angular 2 - bind object to dropdown and select value based on an event

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>


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.

First Attempt:

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


Second Attempt:

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){}
}


Third Attempt:

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...

enter image description here

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

Answer

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.