How to change text shown on ion-select when value is changed?

I have a select in my code that looks like this.

              <ion-select formControlName="location" (click)="clearSectionAndTask()">
                <ion-select-option *ngFor="let location of locations" value="{{location.locationId}}">
                  {{location.locationName}}
                </ion-select-option>
              </ion-select>

The list of locations is retrieved from an API in JSON format.
The user is able to select a default location from the settings page which should then pre-select the drop down for him.

    this.settings.getStandardLocation().then(val => {
      if (val) {
        this.formGroup.patchValue({location: val.id});
      }
    });

Doing it like this has the expected result of changing the value of the drop down to the correct id, but doesn’t actually select and thus change the value shown on the select itself.

Doing it with patchValue({location: val}) results into the value being set to the object rather than the id.

What is the right way to solve this?

Thanks.

Hmm. Is there a chance your problem actually lies elsewhere? The following acts like it sounds like you are expecting for me (unless I’m misunderstanding you, which is entirely possible):

export class HomePage {
  fruits = [{id: "a", name: "apple"}, {id: "b", name: "banana"}, {id: "c", name: "cherry"}];
  fg = new FormGroup({fruit: new FormControl()});

  pickBanana(): void {
    this.fg.patchValue({fruit: "b"});
  }
}
<ion-content>
    <form [formGroup]="fg">
        <ion-item>
            <ion-select formControlName="fruit">
                <ion-select-option *ngFor="let fruit of fruits" [value]="fruit.id">
                    {{fruit.name}}
                </ion-select-option>
            </ion-select>
        </ion-item>
    </form>
    <ion-button (click)="pickBanana()">pick banana</ion-button>
</ion-content>
1 Like

Your example works for me too, which leaves me confused as to why I don’t get the same behavior in my own app. Might it have something to do with my formgroup definition?

   this.formGroup = formBuilder.group({
      location: ['', [Validators.required, Validators.minLength(1)]],
      section: ['', [Validators.required, Validators.minLength(1)]],
      task: ['', [Validators.required, Validators.minLength(1)]],
    });

Yep, turns out i forgot the square brackets around value. Woop.

1 Like