@@ -123,6 +123,31 @@ import { SelectPopover, SelectPopoverOption } from './select-popover-component';
123
123
* };
124
124
* ```
125
125
*
126
+ * ### Object Value References
127
+ *
128
+ * When using objects for select values, it is possible for the identities of these objects to
129
+ * change if they are coming from a server or database, while the selected value's identity
130
+ * remains the same. For example, this can occur when an existing record with the desired object value
131
+ * is loaded into the select, but the newly retrieved select options now have different identities. This will
132
+ * result in the select appearing to have no value at all, even though the original selection in still intact.
133
+ *
134
+ * Using the `compareWith` `Input` is the solution to this problem
135
+ *
136
+ * ```html
137
+ * <ion-item>
138
+ * <ion-label>Employee</ion-label>
139
+ * <ion-select [(ngModel)]="employee" [compareWith]="compareFn">
140
+ * <ion-option *ngFor="let employee of employees" [value]="employee">{{employee.name}}</ion-option>
141
+ * </ion-select>
142
+ * </ion-item>
143
+ * ```
144
+ *
145
+ * ```ts
146
+ * compareFn(e1: Employee, e2: Employee): boolean {
147
+ * return e1 && e2 ? e1.id === e2.id : e1 === e2;
148
+ * }
149
+ * ```
150
+ *
126
151
* @demo /docs/demos/src/select/
127
152
*/
128
153
@Component ( {
@@ -153,6 +178,7 @@ export class Select extends BaseInput<any> implements OnDestroy {
153
178
_overlay : ActionSheet | Alert | Popover ;
154
179
_texts : string [ ] = [ ] ;
155
180
_text : string = '' ;
181
+ _compareWith : ( o1 : any , o2 : any ) => boolean = isCheckedProperty ;
156
182
157
183
/**
158
184
* @input {string} The text to display on the cancel button. Default: `Cancel`.
@@ -187,6 +213,18 @@ export class Select extends BaseInput<any> implements OnDestroy {
187
213
*/
188
214
@Input ( ) selectedText : string = '' ;
189
215
216
+ /**
217
+ * @input {Function} The function that will be called to compare object values
218
+ */
219
+ @Input ( )
220
+ set compareWith ( fn : ( o1 : any , o2 : any ) => boolean ) {
221
+ if ( typeof fn !== 'function' ) {
222
+ throw new Error ( `compareWith must be a function, but received ${ JSON . stringify ( fn ) } ` ) ;
223
+ }
224
+ this . _compareWith = fn ;
225
+ }
226
+
227
+
190
228
/**
191
229
* @output {any} Emitted when the selection was cancelled.
192
230
*/
@@ -448,7 +486,7 @@ export class Select extends BaseInput<any> implements OnDestroy {
448
486
this . _options . forEach ( option => {
449
487
// check this option if the option's value is in the values array
450
488
option . selected = this . getValues ( ) . some ( selectValue => {
451
- return isCheckedProperty ( selectValue , option . value ) ;
489
+ return this . _compareWith ( selectValue , option . value ) ;
452
490
} ) ;
453
491
454
492
if ( option . selected ) {
0 commit comments