1

I'm trying to build a form with State and City fields, so when I change a State, the cities from that selected State are loaded:

<ion-item>
  <ion-label stacked>State*</ion-label>
  <ion-select formControlName="stateId" (ionChange)="updateCities()">
    <ion-option *ngFor="let state of states" value="{{state.id}}">{{state.name}}</ion-option>
  </ion-select>
</ion-item>
<ion-item>
  <ion-label stacked>City*</ion-label>
  <ion-select formControlName="cityId">
    <ion-option *ngFor="let city of cities" value="{{city.id}}">{{city.name}}</ion-option>
  </ion-select>
</ion-item>

Ts file:

  updateCities() {
    let state_id = this.formGroup.value.stateId;
    this.cityService.findAll(state_id)
      .subscribe(response => {
        this.cities= response;
        this.formGroup.value.cityId = this.cities[0].id;
      });
  }

Notice I'm also forcing my formGroup.value.cityId to be set as the first city from the new loaded collection (I'm not sure if it is a good practice). However, no city is selected in the ion-select. So how can I force the selection of cities[0] in my ion-select when I change a State in my form?

Nelio Alves
  • 1,231
  • 13
  • 34

0 Answers0