@@ -5,7 +5,13 @@ import {
5
5
dispatchEvent ,
6
6
dispatchKeyboardEvent ,
7
7
} from '@angular/cdk/testing' ;
8
- import { Component , DebugElement , ChangeDetectionStrategy } from '@angular/core' ;
8
+ import {
9
+ Component ,
10
+ DebugElement ,
11
+ ChangeDetectionStrategy ,
12
+ QueryList ,
13
+ ViewChildren ,
14
+ } from '@angular/core' ;
9
15
import { async , ComponentFixture , fakeAsync , TestBed , tick , flush } from '@angular/core/testing' ;
10
16
import { By } from '@angular/platform-browser' ;
11
17
import {
@@ -620,6 +626,7 @@ describe('MatSelectionList with forms', () => {
620
626
SelectionListWithPreselectedOption ,
621
627
SelectionListWithPreselectedOptionAndModel ,
622
628
SelectionListWithPreselectedFormControlOnPush ,
629
+ SelectionListWithCustomComparator ,
623
630
]
624
631
} ) ;
625
632
@@ -842,6 +849,24 @@ describe('MatSelectionList with forms', () => {
842
849
} ) ) ;
843
850
844
851
} ) ;
852
+
853
+ describe ( 'with custom compare function' , ( ) => {
854
+ it ( 'should use a custom comparator to determine which options are selected' , fakeAsync ( ( ) => {
855
+ const fixture = TestBed . createComponent ( SelectionListWithCustomComparator ) ;
856
+ const testComponent = fixture . componentInstance ;
857
+
858
+ testComponent . compareWith = jasmine . createSpy ( 'comparator' , ( o1 , o2 ) => {
859
+ return o1 && o2 && o1 . id === o2 . id ;
860
+ } ) . and . callThrough ( ) ;
861
+
862
+ testComponent . selectedOptions = [ { id : 2 , label : 'Two' } ] ;
863
+ fixture . detectChanges ( ) ;
864
+ tick ( ) ;
865
+
866
+ expect ( testComponent . compareWith ) . toHaveBeenCalled ( ) ;
867
+ expect ( testComponent . optionInstances . toArray ( ) [ 1 ] . selected ) . toBe ( true ) ;
868
+ } ) ) ;
869
+ } ) ;
845
870
} ) ;
846
871
847
872
@@ -1004,3 +1029,23 @@ class SelectionListWithPreselectedFormControlOnPush {
1004
1029
opts = [ 'opt1' , 'opt2' , 'opt3' ] ;
1005
1030
formControl = new FormControl ( [ 'opt2' ] ) ;
1006
1031
}
1032
+
1033
+
1034
+ @Component ( {
1035
+ template : `
1036
+ <mat-selection-list [(ngModel)]="selectedOptions" [compareWith]="compareWith">
1037
+ <mat-list-option *ngFor="let option of options" [value]="option">
1038
+ {{option.label}}
1039
+ </mat-list-option>
1040
+ </mat-selection-list>`
1041
+ } )
1042
+ class SelectionListWithCustomComparator {
1043
+ @ViewChildren ( MatListOption ) optionInstances : QueryList < MatListOption > ;
1044
+ selectedOptions : { id : number , label : string } [ ] = [ ] ;
1045
+ compareWith ?: ( o1 : any , o2 : any ) => boolean ;
1046
+ options = [
1047
+ { id : 1 , label : 'One' } ,
1048
+ { id : 2 , label : 'Two' } ,
1049
+ { id : 3 , label : 'Three' }
1050
+ ] ;
1051
+ }
0 commit comments