使用angular2

时间:2017-04-24 09:27:54

标签: arrays angular typescript

我在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;
&#13;
&#13;

1 个答案:

答案 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策略。