I am facing issue with ion-select(array objects) (multiple select). Two items are already selected on page load, but when you open the drop-down, none of the items are checked. Here is stackblitz link to reproduce this issue.
https://stackblitz.com/edit/ionic-angular-v5-kie1wd
I am using Ionic(5.26.0) and angular(8.2.14) for my project.
<ion-item>
<ion-label>Users(Multi)</ion-label>
<ion-select multiple="true" [(ngModel)]="selectedMultipleEmployee" [compareWith]="compareFn"
(ionChange)="multiChange()">
<ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}
</ion-select-option>
</ion-select>
</ion-item>
compareFn(e1: User, e2: User): boolean {
return e1 && e2 ? e1.id === e2.id : e1 === e2;
}


TL;DR
Your
compareWith(e1, e2)function must returntrueife2is an array and a single elemente1is ine2, for example:Important: also, define your function
compareWithoutside of the class, otherwise it does not workBackground
I've had the same issue after upgrading from Ionic3 to Ionic5, and I've debugged the
ion-selectcode to see what's causing this issue.Here's the function that determines if the an option must be checked or unchecked:
The
compareValueis an array and the finalelseclause handles that case ifcompareWithis not provided. But since you provide your owncompareWithfunction, then it has to be able to check if a single items belongs to that array.Here's the actual code that worked for my specific case (comparing items by field
code):Update: Added a note that
compareWithneeds to be defined outside of the class.