I'm trying to set the default value of a select tag containing objects in a form, using [selected] and [ngValue]. But for some reason they seem incompaptible.
Example code:
<select id="selectedStore" *ngIf="showStore"
class="form-control"
formControlName="homeStore"
tabindex="{{getTabIndex('homeStore')}}">
<option *ngFor="let store of availableStores"
[ngValue]="store"
[selected]="store.storeId == personalInfo.homeStore?.storeId">
{{store.name}}
</option>
</select>
This code ends up just showing blank as the default value. If I remove the [ngValue] it works fine, except that then it's the store.name value that gets selected, instead of the store object.
Any suggestions?
You can use compareWith
with [ngValue]
eg:
<select id="selectedStore" *ngIf="showStore"
class="form-control"
formControlName="homeStore"
tabindex="{{getTabIndex('homeStore')}}" [compareWith]="compareByID">
<option *ngFor="let store of availableStores"
[ngValue]="store">
{{store.name}}
</option>
</select>
compareByID(itemOne, itemTwo) {
return itemOne && itemTwo && itemOne.ID == itemTwo.ID;
}
See: https://github.com/angular/angular/pull/13349
Example Compare select options: http://blog.ninja-squad.com/2017/03/24/what-is-new-angular-4/
Note: this support is added in Angular4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With