我在angular2中使用ng-model下拉,当我更改模型时,我的视图没有更新
//intialize the variable
addplanhours:any[];
this.addplanhours=[{name: '--sel--',value:0}, {name: 'Head start',value:1}, {name: 'Nice going',value:2},{name: 'On Track',value:3},{name: 'Keep On trying',value:4},{name: 'Making process',value:5},{name: 'Wrapping up',value:6}];
//function of electrifyonchange
electrifyonChange(value) {
for(var i=0;i<=this.addplanhours.length;i++){
this.electrify= value;
console.log("new value",this.electrify);
}
&#13;
<span>
<span class="addnotefont1">Electrifying</span>
<select class="addplanpicker"[(ngModel)]="electrify" (ngModelChange)="electrifyonChange($event)">
<option *ngFor="let a of addplanhours" [ngValue]="a.value">{{a.name}} </option>
</select>
</span>
&#13;
答案 0 :(得分:0)
[ngValue]
可以包含任何类型的对象或值,因此您可以使用[compareWith]
函数来维护下拉状态,因为您正在使用对象:
<select class="addplanpicker" [(ngModel)]="electrify" [compareWith]="isplanHourSelected">
<option *ngFor="let a of addplanhours" [ngValue]="a">{{a.name}} </option>
</select>
isplanHourSelected(o1, o2) {
return o1 && o2 && o1.value == o2.value
}
您现在将获得electrify
所选对象,如果您想在electrify中选择任何值时运行特定事件,则可以使用OnChange策略。