Skip to content

Commit 119005e

Browse files
committed
fix(a11y): inconsistent runtime value for ListKeyManager.activeItem
The `activeItem` is currently typed to `T | null`, however on init and when assigning incorrect values, the `activeItem` will actually be `undefined` at runtime. These changes add some logic to make sure that the value is consistent with its type. Fixes #14152.
1 parent 39888f3 commit 119005e

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/cdk/a11y/key-manager/list-key-manager.spec.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,15 @@ describe('Key managers', () => {
9393
expect(keyManager.activeItem!.getLabel()).toBe('one');
9494
});
9595

96+
it('should start off the activeItem as null', () => {
97+
expect(new ListKeyManager([]).activeItem).toBeNull();
98+
});
99+
100+
it('should set the activeItem to null if an invalid index is passed in', () => {
101+
keyManager.setActiveItem(1337);
102+
expect(keyManager.activeItem).toBeNull();
103+
});
104+
96105
describe('Key events', () => {
97106

98107
it('should emit tabOut when the tab key is pressed', () => {

src/cdk/a11y/key-manager/list-key-manager.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shif
3939
*/
4040
export class ListKeyManager<T extends ListKeyManagerOption> {
4141
private _activeItemIndex = -1;
42-
private _activeItem: T;
42+
private _activeItem: T | null = null;
4343
private _wrap = false;
4444
private _letterKeyStream = new Subject<string>();
4545
private _typeaheadSubscription = Subscription.EMPTY;
@@ -307,9 +307,11 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
307307
updateActiveItem(item: any): void {
308308
const itemArray = this._getItemsArray();
309309
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
310+
const activeItem = itemArray[index];
310311

312+
// Explicitly check for `null` and `undefined` because other falsy values are valid.
313+
this._activeItem = activeItem == null ? null : activeItem;
311314
this._activeItemIndex = index;
312-
this._activeItem = itemArray[index];
313315
}
314316

315317
/**

0 commit comments

Comments
 (0)