77 */
88
99import { QueryList } from '@angular/core' ;
10- import { Observable , Subject } from 'rxjs' ;
10+ import { isObservable , Observable , Subject } from 'rxjs' ;
1111
1212// TODO(cassc): Temporarily disable tslint since this is just the raw API.
1313// tslint:disable
@@ -91,7 +91,23 @@ export interface TreeKeyManagerOptions<T extends TreeKeyManagerItem> {
9191 * keyboard events occur.
9292 */
9393export 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+ }
95111
96112 /**
97113 * Stream that emits any time the TAB key is pressed, so components can react
@@ -113,12 +129,22 @@ export class TreeKeyManager<T extends TreeKeyManagerItem> {
113129
114130 /** Index of the currently active item. */
115131 getActiveItemIndex ( ) : number | null {
116- return null ;
132+ return this . _activeItemIndex ;
117133 }
118134
119135 /** The currently active item. */
120136 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+ }
122148 }
123149}
124150
0 commit comments