John John - 1 year ago 113
AngularJS Question

Select not changing

I have a selection hooked up to my model that has a key and value. I have a ngModelChange hooked up to a function to check what the selection value is. The selection shows the key to the user and the model change shows the value to the controller. However, when i try to get the Key from selection model is just shows the value that i instantiated it to. How do i get the key from my selection?


<select name="sel1" class="form-control" [ngModel]="selectedItem" (ngModelChange)="onChange($event)" >
<option [value]="item.value" *ngFor="let item of items">{{item.key}}</option>


private items:Array<any> = [
{ key:"Price", value:"itemPrice" },
{ key:"Year Made", value:"itemYear" },
{ key:"Model", value:"itemModel" },
{ key:"Customer Rating", value:"itemRating" },
{ key:"Newest Arrivals", value:"itemNewAriv" },
private selectedItem = this.items[0];
onChange(value) {
console.log(this.selectedItem.key); // Does not change

Answer Source

If item is an object (not a string) then [ngValue] should be used instead of [value]:

 <option [ngValue]="item" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download