我正在构建一个,并且正在使用FormArray向campus
添加多个school
。每个campus
都有一个用于country
,state
和city
的选择输入,它们是动态的,并在change
上发出API GET请求。
问题在于,当我更改Campus 2的国家/地区时,更改功能会发出请求并更新两个Campus的州列表。
如何为每个校园创建不同的州和城市阵列?
HTML文件
<form [formGroup]="campusInformationForm" (ngSubmit)="onSubmit(campusInformationForm)" novalidate>
<div formArrayName="campuses"
*ngFor="let campus of campusInformationForm.get('campuses')['controls']; let i = index;">
<div class="row" [formGroupName]="i">
<h4 class="large-body--bold">Campus {{i + 1 }}</h4>
<label for="country_id">Country</label>
<select value="" formControlName="country_id"
(change)="getStatesByCountry(campusInformationForm.get('campuses').value[i]['country_id'])">
<option value="" selected disabled>Select a country</option>
<option [value]="country.id" *ngFor="let country of countries">{{country.name}}</option>
</select>
<label for="state_id">State</label>
<select value="" formControlName="state_id"
(change)="getCitiesByState(campusInformationForm.get('campuses').value[i]['state_id'])">
<option value="" selected disabled>Select a state</option>
<option [value]="state.id" *ngFor="let state of states">{{state.name}}</option>
</select>
<label for="city_id">City</label>
<select value="" formControlName="city_id">
<option value="" selected disabled>Select a city</option>
<option [value]="city.id" *ngFor="let city of cities">{{city.name}}</option>
</select>
</div>
</div>
</form>
TS文件
countries: Array<Country>
states: Array<State>
cities: Array<City>
ngOnInit() {
this.getCountries();
this.campusInformationForm = this.fb.group({
campuses: new FormArray([])
})
}
getStatesByCountry(id) {
this.geo.getStatesById(id).subscribe(response => {
this.states = response['states'];
}, error => {
console.log(error);
})
}
getCitiesByState(id) {
this.geo.getCitiesById(id).subscribe(response => {
this.cities = response['cities'];
}, error => {
console.log(error);
})
}
private getCountries() {
this.geo.getCountries().subscribe(response => {
this.countries = response['countries'];
}, error => {
console.log(error);
})
}
如果更改国家/地区,我希望仅校园2的州选项列表会更新。但是,当我更改两个校园的任何一个国家/地区时,两个州的列表都会更新。