How to select an option from an ion-select programatically?

I have an ion-select with options pulled from an array in an API using a provider. I also use Geolocation and Geo encoding native modules to validate some data from the array. What I want to do is make this function automatically select the corresponding option in the ion-select when executed.

HTML

<ion-item class="select select-province">
     <ion-label class="select-label">Provincia</ion-label>
     <ion-select [(ngModel)]="selectProvince.kind" (ionChange)="selectedProvince(selectProvince)">
       <ion-option *ngFor="let item of provinceList" [value]="item.province_id" class="province-item">{{item.province_name}}</ion-option>
     </ion-select>
   </ion-item>

TS

geoEncode(position){
    this.nativeGeocoder.reverseGeocode(position.coords.latitude, position.coords.longitude)
    .then((resp)=>{
      var indexGeo = this.provinceList.findIndex(i => i.province_name === resp.administrativeArea);
      console.log(indexGeo);
      if (indexGeo < 0){
        let alert = this.alertCtrl.create({
          title: 'InformaciĂłn',
          subTitle: 'No exsisten coincidencias con su ubicaciĂłn actual.',
          buttons: ['OK']
        });
        alert.present();
      }
    })
  }
}

What I want to do is use the index obtained in indexGeo to select the option in that index in the ion-select above.

Thanks for the help!!!

Generally you don’t want both (ionChange) and [(ngModel)] on the same element. All you have to do to seed the select is to assign the desired value to selectProvince.kind.

Care to illustrate me? I don’t know how.
Thanks so much!!

Regarding the ionChange and ngModel I use them to trigger some events within my app. So I need them to be there. Is there a problem with that and what I’m trying to do?

AFAIK using ngModel and ionChange should not be a problem. I’m using them in a same scenario as you- saving the new value into a variable by ngModel and trigger some other action by ionChange.

[(ngModel)] is a two way binding. When you select a value from the list, ionic will write the value of the selected item into the variable indicated in ngModel. On the other side, if you programmatically set the variable to a value, the ion-select will directly show you this value as selected.

So, if you change the value of selectProvince.kind inside your TS code, the component will show this item as selected.

Thanks for the quick reply.

My ion-select already has items in it, items pulled from an external array using a provider. I validated if this.provinceList has an item with a resp.administrativeArea string value in it and then gets the index indexGeo of that element in the array if successful. I don’t want to push a new value in the ion-select. just select the one that’s located in the index obtained.

The reason I want to do this is because it triggers another action based on an ID item.province_id pulling data and populating another ion-select.

Thanks for the help!

let me try with an example

.html:

<ion-select ([ngModel])=“selectedItem” (ionChange)=“onItemSelection(selection)”>
<ion-option *ngFor=“let item of itemsArray” [value]=“item.id”>
{{item.name}}

.ts:

public itemsArray;
public selectedItem;

constructor() {
loadItems(); // load the possible item- ion-options
this.selectedItem = itemsArray[4]; // select the 4th option. In your app the 4th option will be selected
this.selectedItem = undefined; // now no more item is selected
}

private loadItems(){
this.itemsArray = ItemsProvider.loadItems();
}
public onItemSelection(selection) {
if ( selection != undefined) {
console.log("item selected: "+item.name);
} else {
console.log(“no item selected”);
}
}

does this help?

2 Likes

It freakin’ worked!!!

Here’s the function at its state:

geoEncode(position){
    this.nativeGeocoder.reverseGeocode(position.coords.latitude, position.coords.longitude)
    .then((resp)=>{
      //console.log(this.provinceList.province_name.indexOf(resp.administrativeArea));
      var indexGeo = this.provinceList.findIndex(i => i.province_name === resp.administrativeArea);
      console.log(indexGeo);

      if (indexGeo < 0){
        let alert = this.alertCtrl.create({
          title: 'InformaciĂłn',
          subTitle: 'No exsisten coincidencias con su ubicaciĂłn actual.',
          buttons: ['OK']
        });
        alert.present();
      }
      else{
        this.selectProvince.kind = this.provinceList[indexGeo].province_id;
        console.log(this.provinceList[indexGeo].province_id);
      }

Thanks for the help! Much appreciated!!

I don’t like having two things with overlapping responsibility in general, because it tends to facilitate bugs when they (intentionally or accidentally) conflict. So if I really need a change handler, I take the output binding off and handle model updates in that change handler.

I think you should use Preformatted text instead of

“Blockquote”

Because of the formatting