I have dropdown using ng-model in angular2 and my view is not updating when I change the 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); }
<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>
[ngValue]
can hold any kind of object or value, so you can use [compareWith]
function to maintain the dropdown state because you are using object:
<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
}
You will get electrify
the selected object now, if you want to run a particular event when any value is selected in electrify then you can use OnChange strategy.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.