How to get data in to select in the form coontrol

Having changes in one select affect the backing model for other selects is tricky, and the best solution I have found to date works like so:

  form: FormGroup;
  countries = ['Afghanistan', 'Azerbaijan', 'Albania'];
  statesByCountry = {
    Afghanistan: ['AfghanA', 'AfghanB', 'AfghanC'],
    Azerbaijan: ['AzerA', 'AzerB', 'AzerC'],
    Albania: ['AlbaA', 'AlbaB', 'AlbaC'],
  };
  states = [];

  constructor(fb: FormBuilder,
              private _cdr: ChangeDetectorRef) {
    this.form = fb.group({
      country: [''],
      state: [''],
    });
  }

  onCountryChange(): void {
    let country = this.form.get('country').value;
    this.states = this.statesByCountry[country];
    this._cdr.detectChanges();
  }
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <ion-item>
      <ion-select formControlName="country" (ionChange)="onCountryChange()">
        <ion-option *ngFor="let country of countries" [value]="country">{{country}}</ion-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select formControlName="state">
        <ion-option *ngFor="let state of states" [value]="state">{{state}}</ion-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <button ion-button>submit</button>
    </ion-item>
  </form>
7 Likes