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

标签 html angular

我正在尝试使用 [selected] 和 [ngValue] 设置包含表单中对象的选择标签的默认值。但出于某种原因,它们似乎不相容。

示例代码:

<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 值,而不是商店对象。

有什么建议吗?

最佳答案

您可以将 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 中添加的

关于html - 在 select 标签中使用 [ngValue] 和 [selected],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299247/

相关文章:

html - css - 如何使两个右侧 div 的高度等于左侧 div 的高度

python - 在 Django 中检索图像

html - Angular 2 : change border color for error in form validation

intellij-idea - IntelliJ 和 Angular2/TypeScript - 错误 TS2307 : Cannot find module 'angular2/...'

所有以 app- 前缀开头的元素的 CSS 选择器

javascript - 响应圈(javascript,html5,css)

html - 尝试使用 Zurb Foundation 使电子邮件在响应列点折叠

javascript - 使 div 仅与父级一样长

javascript - Angular 2 Webworkers Http 未捕获( promise ): not implemented

Angular 单元测试(带 Getter): Error: No value accessor for form control with name