How to set default selected value of ion-option?

If you deal with default value xor objects, the cleanest way is to provide a compare function to the [compareWith] attribute. This function takes 2 objects in parameters and returns true if they are equals. This way, existing values in model will be selected at start. This works too if new data are added in model outside of the select.

Following example is taken from official Ionic doc

<ion-item>
  <ion-label>Employee</ion-label>
  <ion-select [(ngModel)]="employee" [compareWith]="compareFn">
    <ion-option *ngFor="let employee of employees" [value]="employee"></ion-option>
  </ion-select>
</ion-item>

compareFn(e1: Employee, e2: Employee): boolean {
  return e1 && e2 ? e1.id == e2.id : e1 == e2;
}

EDIT : using double equals make it work for Ionic 4 (as Stan Kurdziel suggests in comment)

Leave a Comment