Pre-selecting in ion-select not working with complex types

I have an ion-select object that I am feeding a set of airlines into that is not pre-selecting properly:

The HTML:

<ion-label stacked>Airline</ion-label>
<ion-select [(ngModel)]="location.airline" name="airline">
    <ion-option *ngFor="let airline of airlines" [value]="airline" [selected]="isSelected(airline)">{{airline.name}}</ion-option>
</ion-select>

location.airline is an object that looks like this:

{ name: "Delta Airlines", iata: "DL" }

airlines is an array of airlines like:

[
  { name: "Delta Airlines", iata: "DL" }
]

isSelected() looks like:

isSelected(airline) {
  return airline.iata == this.location.airline.iata;
}

The original code I was testing with had <ion-option ... selected="{{airline.iata==location.airline.iata}}">..., but I moved it to a function to that I could inspect what was happening.

When I load the view, nothing is selected in the select box, even though I confirmed, through inspecting the isSelected() function that Delta returned true. I have tried the suggestions from various past posts without any success.

@davejlong I suspect that the selected field is being ignored and the ngModel value is just being compared with the ion-option value (in my ion-options, I don’t even use the selected field, just the value, and it works).

If this is the case it makes sense, because the objects location.airline and the airline from the airlines list are 2 different instances, although the values in them are the same (they represent the same thing).

You can test it doing in your component class this.location.airline = this.airlines[0] and see if the first option is selected.

1 Like

To build on @lucasbasquerotto’s excellent comment, you can change that behavior by eliminating [(ngModel)] and managing the model binding yourself in an (ionChange) handler. That way your [selected] should become effective.

I was able to fix the logic by implementing in the handler for loading in airlines adding the following logic:

this.location.airline = airlines.find((airline) => {
  return airline.iata == this.location.airline.iata;
});

Would be nice to have compareWith implemented for ion-select component - the same way it’s done for native select in angular 4. All other solutions I saw look more like workarounds.

P. S. actually, maybe it would be better to have compareWith work on the level of ngModel in order to not duplicate code…

1 Like