Search code examples
ionic-frameworkhtml-selectdefault

Ionic Select, change default selected option from script


I'm facing a problem with ionic select options. In a settings popup, I defined a few options and one is selected="true" like the following code:

<ion-select (ionChange)="changeStartpoints($event)" interface="popover">
  <ion-option value="1" selected="true">1</ion-option>
  <ion-option value="2">2</ion-option>
</ion-select>

This works perfectly fine, but now I don't want the first option to be selected by default every time I open the settings popup. If the second option was selected the last time, I want the second option to be pre-selected this time opening the popup.

I tried this:

<ion-select (ionChange)="changeStartpoints($event)" interface="popover">
  <ion-option value="1" selected="isSelected_Startpoints(170)">1</ion-option>
  <ion-option value="2" selected="isSelected_Startpoints(501)">2</ion-option>
</ion-select>

where isSelected_Startpoints() is:

isSelected_Startpoints (value: number) {
  console.log(this.startpoints);
  if (this.startpoints == value) {
    return true;
  } else {
    return false;
  }
}

and changeStartpoints() is:

changeStartpoints (change) {
  change = parseInt(change);
  this.startpoints = change;
}

but it did not work. Not even the console.log appeared.

So my question is, Is it possible to link functions to the "selected" attribute? And how can I solve my problem?

Thanks for any help


Solution

  • Give something like this a try:

    <ion-select (ionChange)="changeStartpoints($event)" interface="popover">
        <ion-option value="1" selected="{{startpoints === 170}}">1</ion-option>
        <ion-option value="2" selected="{{startpoints === 501}}">2</ion-option>
    </ion-select>
    

    My guess is your version may have worked if you changed your selected to [selected] too