我正在尝试设置下拉列表的默认值,我将模型设置为默认值但不更新选择
请参阅此https://plnkr.co/edit/bNM5Yxx78iykv2opazoL?p=preview
@Component({
selector: 'my-app',
template: `
<h1>Hello</h1>
<select class="form-control selectpicker" (change)="changeTower()" [(ngModel)]="_selectedTower">
<option attr.value="{{tower._id}}" *ngFor="#tower of _towers;">Tower {{tower.name}}</option>
</select>
`})
export class AppComponent {
_towers = [{_id:1, name: '1'}, {_id:2, name: '2'}, {_id:3, name: '3'}];
constructor() {
this._selectedTower = 2 ;
}
changeTower() {
setTimeout(()=>{
alert( this._selectedTower);
},100);
}
答案 0 :(得分:1)
如果_selectedTower
指的是对象而不是原始值(_towers
相同 - 对象数组而不是原始值),则使用ngValue
代替value
<select class="form-control selectpicker" (change)="changeTower()" [(ngModel)]="_selectedTower">
<option [ngValue]="tower" *ngFor="let tower of _towers;">Tower {{tower.name}}</option>
</select>
答案 1 :(得分:1)
您需要以这种方式使用ngValue作为选项:
<select class="form-control selectpicker" (change)="changeTower()" [(ngModel)]="_selectedTower">
<option [ngValue]="tower._id" *ngFor="#tower of _towers;">Tower {{tower.name}}</option>
</select>
请参阅此plunkr:https://plnkr.co/edit/UC5iYQUIFIrQMNeYbSQy?p=preview。
答案 2 :(得分:0)
<select class="form-control selectpicker" #select (change)="changeTower(select.value)" [(ngModel)]="_selectedTower">
<option value="{{tower._id}}" *ngFor="#tower of _towers;">Tower {{tower.name}}</option>
</select>
changeTower(id) {
//id is the selected value
}