我有两个选择输入:国家和城市。 我想在改变国家后改变城市,但只有在我打开城市选择两次之后才会改变它们。 似乎在我选择国家之后,ngFor cycle不会立即运行。
如何在选择国家/地区后立即更改城市选项?
<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>
答案 0 :(得分:1)
您可以使用change
指令。
这是一个如何做到这一点的例子。首先,您必须构建一个自定义函数来过滤每个国家/地区的城市
<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
}