Angular 7:FormArray +选择更改+ GET请求

时间:2019-06-24 22:04:22

标签: angular typescript frontend

我正在构建一个,并且正在使用FormArray向campus添加多个school。每个campus都有一个用于countrystatecity的选择输入,它们是动态的,并在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的州选项列表会更新。但是,当我更改两个校园的任何一个国家/地区时,两个州的列表都会更新。

0 个答案:

没有答案