Search code examples
angulartypescriptionic2ionic3

ion-select select default value not working


I have ion-select with that have many options and I have when the view is ready to select one default value depending on CurrentNumber. i have this code:

<ion-select formControlName="Level">
          <ion-option [value]="level.id" *ngFor="let level of levels" [attr.selected]="(level.levelNumber == currentLevel)? true : null">
             {{level.name}}
          </ion-option>
</ion-select>

this.currentLevel = 1;

the data comes from the server like that :

data = [
 {
  levelNumber : 1,
  name:'abcd'
 },
 {
levelNumber:2,
name:'efg'
 }
]

Solution

  • Instead of the selected attribute, you can set the default option in the control when the data is ready:

    // When the data is ready
    this.yourForm.get('Level').setValue(data.id);
    

    That will set the option with id equal to data.id as the default.