Angular 2:尽管 "selected" 属性,Select 下拉菜单未选择选项

Angular 2: Select dropdown not selecting option despite "selected" attribute

我有以下用于 select 下拉列表的代码:

<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" 包含应 selected 的项目的值。在此特定示例中,该值为 3,因此第 3 项应为 selected。果然,当我检查元素时,它在正确的项目上显示 ng-reflect-selected="true",但实际上什么都没有 selected。我怎样才能使列表中的正确项目真正动态 select 而不是仅仅添加 ng-reflect-selected="true" 属性?

attr.selected 绑定将属性值设置为传递的值。因此,如果您传递 false,它将设置 selected="false",这不是您想要的(因为它实际上根据 HTML 规范选择了元素)。要删除属性,您必须传递 null.

使用:

[attr.selected]="unit.Selected ? '' : null"

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

它具有与 *ngFor 中使用的 相同的 实例,这一点很重要。一些其他具有相同属性和相同值的对象实例将不起作用。