Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use [ngValue] and [selected] in select tag

Tags:

html

angular

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?

like image 586
TheFisherman Avatar asked Dec 23 '16 10:12

TheFisherman


1 Answers

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

like image 86
Touqeer Shafi Avatar answered Sep 19 '22 13:09

Touqeer Shafi