在select标签中使用[ngValue]和[selected]

The*_*man 8 html angular

我正在尝试使用[selected]和[ngValue]设置包含表单中对象的select标签的默认值.但由于某些原因,它们似乎无法容忍.

示例代码:

<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>
Run Code Online (Sandbox Code Playgroud)

此代码最终只显示空白作为默认值.如果我删除[ngValue]它可以正常工作,除了它是被选中的store.name值,而不是store对象.

有什么建议?

Tou*_*afi 9

你可以用compareWith[ngValue]

例如:

<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;
}
Run Code Online (Sandbox Code Playgroud)

参见:https : //github.com/angular/angular/pull/13349

示例比较选择的选项:http : //blog.ninja-squad.com/2017/03/24/what-is-new-angular-4/

注意:此支持已在Angular4中添加


Gün*_*uer 8

[ngValue]="..."应该与一起使用[(ngModel)][selected]不适用于[ngValue]


San*_*per 5

如下更新您的选择标签,ngModel将保留选择的值

<select [(ngModel)]="selectedItem.Page.ID" class="form-control" (change)="OnPageSelected($event.target.value)">
    <option *ngFor="let page of PageCollection.Items;" value={{page.ID}}>
        {{page.Name}}
    </option>
</select>
Run Code Online (Sandbox Code Playgroud)