Ion-option pre-selection not working

Hello All,
I’m using this example from ionicframework docs:
Im having a for loop for ion options and which should be preselected when the page loads, the preselection is not working. Please help!

I’m using this code in my html:

Hair Color
<ion-select [(ngModel)]=“hairColor” okText=“Okay” cancelText=“Dismiss”>
<ion-option *ngFor=“let o of hairColorData” [value]=“o”>{{o.text}}

and this in my ts file:

this.hairColorData = [
  { text: 'Brown', value: 'brown' },
  { text: 'Blonde', value: 'blonde' },
  { text: 'Black', value: 'black' },
  { text: 'Red', value: 'red' }
];

// Pre-selected object with different object reference      
this.hairColor = { text: 'Brown', value: 'brown' };

I am having the same problem

OP described the problem: JavaScript does not treat different objects with identical properties as equal.

@charlestsmith @gtripoli You should use the value of the ion-option in the ngModel, not the whole object:

<ion-select [(ngModel)]=“hairColorValue” okText=“Okay” cancelText=“Dismiss”>
<ion-option *ngFor=“let o of hairColorData” [value]=“o.value”>{{o.text}}

And in the ts file:

this.hairColorData = [
  { text: 'Brown', value: 'brown' },
  { text: 'Blonde', value: 'blonde' },
  { text: 'Black', value: 'black' },
  { text: 'Red', value: 'red' }
];

// Pre-selected value (id, unique vlaue)
this.hairColorValue = 'brown';
1 Like

@lucasbasquerotto @rapropos I guess my issue is actually a little different. I probably should start a new thread.

Pre-selection is actually working, technically, for me. The control has the value, however the view is not being updated with the text of the selection. I have tried all sorts of different ways to get the ion-select control to update it’s view (setTimeout, NgZone.run, updating the FormControl value, updating the control directly, etc…). The only way that seems to work is to inject ChangeDetectorRef and call detectChanges on it after setting the value of the control.

If you are doing something like this, that’s probably your best option.

1 Like