@@ -3,6 +3,16 @@ import {FormControl, NgModel} from '@angular/forms';
3
3
import 'rxjs/add/operator/startWith' ;
4
4
import 'rxjs/add/operator/map' ;
5
5
6
+ interface State {
7
+ code : string ;
8
+ name : string ;
9
+ }
10
+
11
+ interface StateGroup {
12
+ letter : string ;
13
+ states : State [ ] ;
14
+ }
15
+
6
16
@Component ( {
7
17
moduleId : module . id ,
8
18
selector : 'autocomplete-demo' ,
@@ -13,6 +23,7 @@ import 'rxjs/add/operator/map';
13
23
export class AutocompleteDemo {
14
24
stateCtrl : FormControl ;
15
25
currentState = '' ;
26
+ currentGroupedState = '' ;
16
27
topHeightCtrl = new FormControl ( 0 ) ;
17
28
18
29
reactiveStates : any ;
@@ -22,7 +33,9 @@ export class AutocompleteDemo {
22
33
23
34
@ViewChild ( NgModel ) modelDir : NgModel ;
24
35
25
- states = [
36
+ groupedStates : StateGroup [ ] ;
37
+ filteredGroupedStates : StateGroup [ ] ;
38
+ states : State [ ] = [
26
39
{ code : 'AL' , name : 'Alabama' } ,
27
40
{ code : 'AK' , name : 'Alaska' } ,
28
41
{ code : 'AZ' , name : 'Arizona' } ,
@@ -82,18 +95,41 @@ export class AutocompleteDemo {
82
95
. startWith ( this . stateCtrl . value )
83
96
. map ( val => this . displayFn ( val ) )
84
97
. map ( name => this . filterStates ( name ) ) ;
98
+
99
+ this . filteredGroupedStates = this . groupedStates = this . states . reduce ( ( groups , state ) => {
100
+ let group = groups . find ( g => g . letter === state . name [ 0 ] ) ;
101
+
102
+ if ( ! group ) {
103
+ group = { letter : state . name [ 0 ] , states : [ ] } ;
104
+ groups . push ( group ) ;
105
+ }
106
+
107
+ group . states . push ( { code : state . code , name : state . name } ) ;
108
+
109
+ return groups ;
110
+ } , [ ] as StateGroup [ ] ) ;
85
111
}
86
112
87
113
displayFn ( value : any ) : string {
88
114
return value && typeof value === 'object' ? value . name : value ;
89
115
}
90
116
91
117
filterStates ( val : string ) {
118
+ return val ? this . _filter ( this . states , val ) : this . states ;
119
+ }
120
+
121
+ filterStateGroups ( val : string ) {
92
122
if ( val ) {
93
- const filterValue = val . toLowerCase ( ) ;
94
- return this . states . filter ( state => state . name . toLowerCase ( ) . startsWith ( filterValue ) ) ;
123
+ return this . groupedStates
124
+ . map ( group => ( { letter : group . letter , states : this . _filter ( group . states , val ) } ) )
125
+ . filter ( group => group . states . length > 0 ) ;
95
126
}
96
127
97
- return this . states ;
128
+ return this . groupedStates ;
129
+ }
130
+
131
+ private _filter ( states : State [ ] , val : string ) {
132
+ const filterValue = val . toLowerCase ( ) ;
133
+ return states . filter ( state => state . name . toLowerCase ( ) . startsWith ( filterValue ) ) ;
98
134
}
99
135
}
0 commit comments