角度2:尽管“已选择",选择下拉菜单仍未选择选项.属性 [英] Angular 2: Select dropdown not selecting option despite "selected" attribute

查看:91
本文介绍了角度2:尽管“已选择",选择下拉菜单仍未选择选项.属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于选择下拉菜单,我有以下代码:

<select id="UnitOfMeasurementId" name="UnitOfMeasurementId" [(ngModel)]="UnitOfMeasurementId">
    <option *ngFor="let unit of UnitOfMeasurements" [ngValue]="unit.Value" [selected]="unit.Selected">{{unit.Text}}</option>
</select>

UnitOfMeasurements数组中的每个项目看起来都像这样:

Selected: false
Text: "lb"
Value: "1"

或者这个:

Selected: true
Text: "kg"
Value: "3"

[(ngModel)]="UnitOfMeasurementId"包含应选择的项目的值.在此特定示例中,该值为3,因此应选择第3个项目.果然,当我检查元素时,它在正确的项目上显示ng-reflect-selected="true",但实际上未选择任何内容.如何获得列表中正确的条目以进行实际动态选择,而不仅仅是添加ng-reflect-selected="true"属性?

解决方案

不要将selected属性与ngModelngValue一起使用,而是将所选项目的值分配给UnitOfMeasurementId. /p>

具有相同实例作为*ngFor中使用的实例非常重要.具有相同属性和相同值的其他一些对象实例将不起作用.

I have the following code for a select dropdown:

<select id="UnitOfMeasurementId" name="UnitOfMeasurementId" [(ngModel)]="UnitOfMeasurementId">
    <option *ngFor="let unit of UnitOfMeasurements" [ngValue]="unit.Value" [selected]="unit.Selected">{{unit.Text}}</option>
</select>

Each item in the UnitOfMeasurements array looks something like this:

Selected: false
Text: "lb"
Value: "1"

Or this:

Selected: true
Text: "kg"
Value: "3"

[(ngModel)]="UnitOfMeasurementId" contains the value of the item that should be selected. In this particular example, that value is 3, so the 3rd item should be selected. Sure enough, when I inspect the element it shows ng-reflect-selected="true" on the correct item, but nothing is actually selected. How can I get the correct item in the list to actually dynamically select instead of just adding the ng-reflect-selected="true" attribute?

解决方案

Don't use the selected attribute with ngModel and ngValue, but instead assign the value of the selected item to UnitOfMeasurementId.

It's important that it has the identical instance as the one used in *ngFor. Some other object instance with the same properties and same values won't work.

这篇关于角度2:尽管“已选择",选择下拉菜单仍未选择选项.属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆