我在 Angular 2 的下拉列表中预选值时遇到了问题。
我在成功绑定到下拉列表的组件中设置了一组颜色。我遇到的问题是在页面 init 上预先选择了一个值。
[selected]="car.color.id == x.id"
应该选择已在汽车型号上设置的值 this.car.color = new Colour(-1,'');
但是这仅在我将汽车颜色 ID 设置为列表中的最后一项时才有效(在此黑色外壳) this.car.color = new Colour(4,'');
我正在使用最新版本的 Angular (rc3),并且在 rc1 和 rc2 中遇到了同样的问题。
这是一个显示问题的plunker。
https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview
另一个奇怪的方面是,在查看元数据时,Angular 将选定的值设置为 true。
但下拉列表仍然显示为空。
这似乎是与这些相关问题不同的问题。
如何在 Angular2 中的对象数组上使用 select/option/NgFor
问候
史蒂夫
组件模板
<div>
<label>Colour</label>
<div>
<select [(ngModel)]="car.colour"">
<option *ngFor="let x of colours" [value]="x.id" [selected]="car.color.id == x.id">{{x.name}}</option>
</select>
</div>
</div>
零件
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
@Component({
selector:'dropdown',
templateUrl:'app/components/dropdown/dropdown.component.html',
directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
car:Car = new Car();
colours = Array<Colour>();
ngOnInit(): void {
this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.colours.push(new Colour(3, 'Orange'));
this.colours.push(new Colour(4, 'Black'));
this.car = new Car();
this.car.color = new Colour(-1,'');
}
}
export class Car
{
color:Colour;
}
export class Colour
{
constructor(id:number, name:string) {
this.id=id;
this.name=name;
}
id:number;
name:string;
}
原文由 CountZero 发布,翻译遵循 CC BY-SA 4.0 许可协议
将
car.colour
设置为您最初选择的值通常是有效的。当设置
car.colour
时,您可以删除[selected]="car.color.id == x.id"
。如果值不是字符串
[ngValue]="..."
必须使用。[value]="..."
只支持字符串。