Set default selected option of ion-select dynamically


#1

Hello Ionites!

I am new to Ionic.

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

Thanks!


#2

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?


#3

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


#4

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>

#5

Hi Stienin

Any luck with this

Also struggling with this


#6

@intelinc

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

Thanks…


#7

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


#8

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…


#10

please tell me how to preselect multiple ion-options