Reputation: 2799
// html code
<select class="form-control form-control-primary"
(change)="changeValue(data)"
[(ngModel)]="data" name="list" id="selectData">
<option *ngFor="let data of dataList" [ngValue]="data">
{{data.name}}
</option>
</select>
// ts code
data: any;
dataList = [{id:1, name:"XYZ"},{id:2,name:"ABC"}];
changeValue(data){
console.log(data); // prints selected data correctly
}
This is sample code just to explain how I had used it in my project. In my case dataList array comes from an API, a grid is displayed at bottom of drop-down which gets updated according to the selected data of dropdown. When other than first data is selected in drop-down and I call API for dataList again to refresh the list, I need the selected prevoius option in drop-down but instead it gets reset to first option.
And I compulsory need to bind object with ngModel Select. Even I tried with ngModelChange, event.target.value but nothing worked for me. I get correct value of data in console but select doesnot get updated.
Upvotes: 0
Views: 1123
Reputation: 3009
After receiving data from the server, write a loop on dataList and compare their Id with the previous one you selected. then bind the object to data
// Assume that you saved previousId in localStorage or
// got it from the server or somewhere else
for (let i = 0; i < this.dataList.length; i++ ) {
if ( this.dataList[i].id == previousId ) {
this.data = this.dataList[i];
}
}
I hope it helps you :)
Upvotes: 2