-
Notifications
You must be signed in to change notification settings - Fork 27k
Description
Hi all,
i'm having a problem with the data binding of SelectedValue of select-option(ComboBox) when I change the DataSource during runtime.
I have a select-option and bind it with a list. The content of the list will be changed during run-time (cleared and inserted with new item). At the beginning I fill the list with these data
mockData1: ListItem[] = [
{ V: "CH", D: "Schweiz" },
{ V: "DE", D: "Deutschland" },
{ V: "VN", D: "Vietnam" }
];
In the UI, I select DE-Deutschland which means that my current selected-value is DE.
Then I clear the list and fill it with other data
mockData2: ListItem[] = [
{ V: "CH", D: "Schweiz" },
{ V: "DE", D: "Deutschland" },
{ V: "VN", D: "Vietnam" },
{ V: "US", D: "USA" }
];
Problem: My current selected-value is still DE, but in the UI nothing is selected.
Question: What should I do so that the databinding still works after I refresh the datasource? Thank you.
I create a sample here https://github.com/rongchaua/angularselect
Or in short version
export class AppComponent implements OnInit {
items: ListItem[] = [];
mockData1: ListItem[] = [
{ V: "CH", D: "Schweiz" },
{ V: "DE", D: "Deutschland" },
{ V: "VN", D: "Vietnam" }
];
mockData2: ListItem[] = [
{ V: "CH", D: "Schweiz" },
{ V: "DE", D: "Deutschland" },
{ V: "VN", D: "Vietnam" },
{ V: "US", D: "USA" }
];
model: string;
constructor(
private http: Http
) {
}
load1() {
console.log("list 1 loaded");
this.items.length = 0;
for (let item of this.mockData1) {
this.items.push(item);
}
}
load2() {
console.log("list 2 loaded");
this.items.length = 0;
for (let item of this.mockData2) {
this.items.push(item);
}
}
ngOnInit(): void {
this.load1();
}
}
<div class="row top-buffer">
<label class="col-md-3" for="">Lala</label>
<div class="col-md-9">
<select class="form-control" name="" [(ngModel)]="model">
<option *ngFor="let item of items" [ngValue]="item.V">{{item.D}}</option>
</select>
</div>
</div>
<div>
{{model}}
</div>
<div>
<button (click)="load1()">Load list 1</button>
<button (click)="load2()">Load list 2</button>
</div>