Set default selected option of ion-select dynamically

Hello Ionites!

I am new to Ionic.

How can I set the default checked option of ion-select dynamically?

Thanks!

1 Like

If you’re using two-way binding with ngModel, seeding that should work:

@Page()
export class FruitStand {
  fruit:string = "banana";
}
<ion-select [(ngModel)]="fruit">
  <ion-option value="apple">apple</ion-option>
  <ion-option value="banana">banana</ion-option>
  <ion-option value="cherimoya">cherimoya</ion-option>
</ion-select>

If you set fruit in the controller code, does that count as “dynamically” for your purposes?

4 Likes

But if I use the object as the value, it does not work. How can I set the initial value?

To preselect an option, you just need to have the ngModel variable == the ion-option value. The select component will automatically take care of the rest. So for the below, if model == ‘my choice’ and category == ‘my choice’ (I set model in ngOnInit() ) then that option will be preselected.

<ion-select [(ngModel)]="model" interface="alert" (ionChange)="enableNextButton()">
<ion-option [value]="category" *ngFor=" let category of industry.categories; let idx = index ">{{category}}</ion-option>
</ion-select>
1 Like

Hi Stienin

Any luck with this

Also struggling with this

@intelinc

How to Pass selected value and Value Index in function enableNextButton()

Thanks…

Same issue here… is there a final answer on this?

Hi @chethankumar_gowda, @mdevalk
The selected value will already be accessible via this.model variable (or whichever variable you are using in the ngModel). When you have the selected value, you can always use javascript’s indexOf function to get the index:
this.industry.categories.indexOf(this.model)

Hope this helps…

please tell me how to preselect multiple ion-options