AJ_
AJ_

Reputation: 3987

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?

Page

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

Component

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("Test"); 
    console.log(value); 
    console.log(this.selectedItem.key);  // Does not change 
}

Upvotes: 0

Views: 38

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

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

 <option [ngValue]="item" 

Upvotes: 1

Related Questions