How to make dynamic selects in Angular2?
Ie there are three selects: country, city, street. When you enter the first select 'country', you need to send a request to the server and select the list of cities belonging to this country to the select 'city'. The same with the street. Thank!
- Give an example of the code that you got, what exactly you can not do? Send requests or fill in lists, etc. - Sergey Glazirin
- I do not understand the logic of the obschik in general. - Alexeev
|
2 answers
Everything is extremely simple:
<select (change)="onChange($event.target.value)"> <option *ngFor="let elem of elements">{{i}}</option> </select> onChange(elemValue) { console.log(elemValue); this.cityService.getCity(elemValue).subscribe( (data) => { const cityname = data.cityName; this.cityService.getStreets(cityname).subscribe( (streetData) => { // где streetData твои улицы. } (error) => { // error } } (error) => { // error } ) } Where elemValue is the select value and instead of cityService and getCity substitute your value.
- Thank! Those. for each city value in select, do you need to write your else if to make a request to the server for the necessary list of cities? - Alexeev
- Oh no, are you now update the answer show how - Zicrael
- I understood, and the request for the streets at the same time with the request for the country to do or load them when the user chooses the city? - Alexeev
- when the user loads the city, of course, now I’ll update the answer as I’m showing you
+:) - Zicrael - And where to put?) - Alexeev
|
Actually it should look something like this:
<select class="form-control input-sm" [(ngModel)]="selectCountryId" (ngModelChange)="changeCountry($event)"> <option [ngValue]="undefined" [textContent]="'Ничего не выбрано'"></option> <option *ngFor='let country of countries' [ngValue]="country.Id" [textContent]="country.Name"></option> </select> <select class="form-control input-sm" [(ngModel)]="selectCityId"> <option [ngValue]="undefined" [textContent]="'Ничего не выбрано'"></option> <option *ngFor='let city of cities' [ngValue]="city.Id" [textContent]="city.Name"></option> </select> In the controller:
changeCountry($event) { this.service.getCities(this.selectCountryId) .subscribe(result => { this.cities = result; }) } Actually the logic is as follows. From the beginning, the default data is loaded. List of countries and a list of cities. Further, as soon as the country is selected, the changeCountry handler is changeCountry . It sends a request to the back-end where the filtering takes place. The resulting list of cities rendiritsya.
- Thank you very much! - Alexeev
|