update
(更新)
4.0.0-beta.6 added compareWith
(4.0.0-beta.6添加了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;
}
this way the instance assigned to selectedCountries
doesn't need to be the identical object, but a custom comparison function can be passed, for example to be able to match an different object instance with identical property values.
(这样,分配给selectedCountries
的实例不必是相同的对象,但是可以传递自定义比较函数,例如,以便能够将具有相同属性值的不同对象实例进行匹配。)
original
(原版的)
If you want to use an object as value you need to use [ngValue]
on the option element.
(如果要将对象用作值,则需要在option元素上使用[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
has an options value assigned [(ngModel)]="..."
will this one make the one selected by default:
(当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];
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…