Skip to content Skip to sidebar Skip to footer

Select --> Option, Using Value Vs Ngvalue

I just recently figured out that there is an alternative for value property on OPTION part of the SELECT, namely ngValue. The docs really lack documentation about this (all I could

Solution 1:

You don't need a "workaround" for that. When you do this

myModel = {id: this.items[1].id , value: this.items[1].value};

you are creating a new object which has the same values as this.items[1] but it is not the same object, it's a new one.

const items = [{id: 1, value: 'item1'}, {id: 2, value: 'item2'}, {id: 3, value: 'item3'}]

const myModel = {id: 2, value: 'item2'};

console.log(items[1] === myModel);

that is the reason why your select can't find that value in the <option> list.

In order to fix that, you have to use a proper reference

items = [
     {id: 1, value: 'item1'},
     {id: 2, value: 'item2'},
     {id: 3, value: 'item3'}
];myModel = this.items[1]

plunkr

Solution 2:

In order to obtain default selected option using [ngValue] you can use [compareWith]. Just change in the method compareObj the correct atribute for the Object your comparing.

<select [compareWith]="compareObj"  [(ngModel)]="selectedObject">
   <option *ngFor="let object of objects" [ngValue]="object">
      {{object.name}}
   </option>
</select>

compareObj(o1: Object, o2: Object) {
   return o1.id === o2.id;
}

Post a Comment for "Select --> Option, Using Value Vs Ngvalue"