Reputation: 63
I have the two select inputs: Country and City. I want to have cities changed after I change country, but they are only changed after I open city select twice. It seems like after I choose country, ngFor cycle is not run immediately.
How can I get changes of cities options immediately after I select a country?
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country" name="country" #countrySelect>
<option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
</select>
</div>
<div class="form-group">
<label for="city">City</label>
<select class="form-control" id="city" name="city" #citySelect [(ngModel)]="publisher.cityId">
<option *ngFor="let city of cities"
[hidden]="countrySelect.value != city.countryId"
[value]="city.id">
{{city.name}}
</option>
</select>
</div>
Upvotes: 2
Views: 10215
Reputation: 1559
You can use change
directive.
Here is an example of how you can do it. First you must build a custom function to filter cities per country
<select (change)="onChange($event.target.value)">
<option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
</select>
<select class="form-control" id="city" name="city" #citySelect [(ngModel)]="publisher.cityId">
<option *ngFor="let city of filteredCities"
[hidden]="countrySelect.value != city.countryId"
[value]="city.id">
{{city.name}}
</option>
allCities = [];
filteredCities = [];
allCountries = [];
onChange(country) {
filteredCities = [];//You empty filterdCities
//Then filter allCities variable according to selected country values and add values to
}
Upvotes: 3