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

时间:2016-12-23 10:04:14

标签: 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>

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

有什么建议吗?

5 个答案:

答案 0 :(得分:7)

[ngValue]="..."应该与[(ngModel)]一起使用。 [selected]无法使用[ngValue]

答案 1 :(得分:7)

您可以将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;
}

请参阅:https://github.com/angular/angular/pull/13349

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

注意:此支持在Angular4中添加

答案 2 :(得分:3)

如下所示更新您的选择标记, 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>

答案 3 :(得分:1)

添加

[ngModel]="yourDefaultObject"

选择,第一个选项相同

答案 4 :(得分:0)

我发布我的询问,因为也许有人正在得到相同的行为。

我从API接收值,我需要分配给表单控件,然后您不能直接分配它。您需要使用相同的availableStores实例数组并在其中查找值。 这就是获得[ngValue]的完美方法。

control.setValue(this.availableStores.find(
  store => store.name === this.valueFromAPI.name
));

<select      
  class="form-control"
  formControlName="homeStore"      
  >
  <option
    *ngFor="let store of availableStores"
    [ngValue]="store">
    {{store.name}}
  </option>
</select>

参考https://angular.io/api/forms/SelectControlValueAccessor检查第一个示例。