update
4.0.0-beta.6 https://github.com/angular/angular/compare/4.0.0-beta.5...4.0.0-beta.6 added compareWith
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
这样实例就分配给了selectedCountries
不需要是相同的对象,但可以传递自定义比较函数,例如能够将具有相同属性值的不同对象实例进行匹配。
original
如果你想使用一个对象作为值,你需要使用[ngValue]
在选项元素上。
<select name="select" id="select" [(ngModel)]="selectLanguage">
<option *ngFor="let item of selectOption" [ngValue]="item"
[disabled]="item.value==0">{{item.label}}</option>
</select>
When selectLanguage
已分配选项值[(ngModel)]="..."
这是否会成为默认选择的一项:
import {Component} from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-form-select',
templateUrl: 'default.component.html'
})
export class DefaultComponent {
private selectOption: any;
constructor() {
this.selectOption = [
{
id: 1,
label: "Select Language",
value: 0
}, {
id: 2,
label: "HTML 5",
value: 1
}, {
id: 3,
label: "PHP",
value: 2
}, {
id: 4,
label: "Javascript",
value: 3
}
];
this.selectLanguage = this.selectOption[0];
}
}