7
7
*/
8
8
9
9
import { QueryList } from '@angular/core' ;
10
- import { Observable , Subject } from 'rxjs' ;
10
+ import { isObservable , Observable , Subject } from 'rxjs' ;
11
11
12
12
// TODO(cassc): Temporarily disable tslint since this is just the raw API.
13
13
// tslint:disable
@@ -91,7 +91,23 @@ export interface TreeKeyManagerOptions<T extends TreeKeyManagerItem> {
91
91
* keyboard events occur.
92
92
*/
93
93
export class TreeKeyManager < T extends TreeKeyManagerItem > {
94
- constructor ( options : TreeKeyManagerOptions < T > ) { }
94
+ private _activeItemIndex = - 1 ;
95
+ private _activeItem : T | null = null ;
96
+
97
+ constructor ( { items} : TreeKeyManagerOptions < T > ) {
98
+ // We allow for the items to be an array or Observable because, in some cases, the consumer may
99
+ // not have access to a QueryList of the items they want to manage (e.g. when the
100
+ // items aren't being collected via `ViewChildren` or `ContentChildren`).
101
+ if ( items instanceof QueryList ) {
102
+ items . changes . subscribe ( ( newItems : QueryList < T > ) => {
103
+ this . _updateActiveItemIndex ( newItems . toArray ( ) ) ;
104
+ } ) ;
105
+ } else if ( isObservable ( items ) ) {
106
+ items . subscribe ( newItems => {
107
+ this . _updateActiveItemIndex ( newItems ) ;
108
+ } ) ;
109
+ }
110
+ }
95
111
96
112
/**
97
113
* Stream that emits any time the TAB key is pressed, so components can react
@@ -113,12 +129,22 @@ export class TreeKeyManager<T extends TreeKeyManagerItem> {
113
129
114
130
/** Index of the currently active item. */
115
131
getActiveItemIndex ( ) : number | null {
116
- return null ;
132
+ return this . _activeItemIndex ;
117
133
}
118
134
119
135
/** The currently active item. */
120
136
getActiveItem ( ) : T | null {
121
- return null ;
137
+ return this . _activeItem ;
138
+ }
139
+
140
+ private _updateActiveItemIndex ( newItems : T [ ] ) {
141
+ if ( this . _activeItem ) {
142
+ const newIndex = newItems . indexOf ( this . _activeItem ) ;
143
+
144
+ if ( newIndex > - 1 && newIndex !== this . _activeItemIndex ) {
145
+ this . _activeItemIndex = newIndex ;
146
+ }
147
+ }
122
148
}
123
149
}
124
150
0 commit comments