From 119005e3e82efa317fe6ee76424c33d35f055e30 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Thu, 15 Nov 2018 22:23:42 +0100 Subject: [PATCH] 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. --- src/cdk/a11y/key-manager/list-key-manager.spec.ts | 9 +++++++++ src/cdk/a11y/key-manager/list-key-manager.ts | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/cdk/a11y/key-manager/list-key-manager.spec.ts b/src/cdk/a11y/key-manager/list-key-manager.spec.ts index 1c1ba2ce8022..4dd870dfb22f 100644 --- a/src/cdk/a11y/key-manager/list-key-manager.spec.ts +++ b/src/cdk/a11y/key-manager/list-key-manager.spec.ts @@ -93,6 +93,15 @@ describe('Key managers', () => { expect(keyManager.activeItem!.getLabel()).toBe('one'); }); + it('should start off the activeItem as null', () => { + expect(new ListKeyManager([]).activeItem).toBeNull(); + }); + + it('should set the activeItem to null if an invalid index is passed in', () => { + keyManager.setActiveItem(1337); + expect(keyManager.activeItem).toBeNull(); + }); + describe('Key events', () => { it('should emit tabOut when the tab key is pressed', () => { diff --git a/src/cdk/a11y/key-manager/list-key-manager.ts b/src/cdk/a11y/key-manager/list-key-manager.ts index ed7b426c6762..0af17b911981 100644 --- a/src/cdk/a11y/key-manager/list-key-manager.ts +++ b/src/cdk/a11y/key-manager/list-key-manager.ts @@ -39,7 +39,7 @@ export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shif */ export class ListKeyManager { private _activeItemIndex = -1; - private _activeItem: T; + private _activeItem: T | null = null; private _wrap = false; private _letterKeyStream = new Subject(); private _typeaheadSubscription = Subscription.EMPTY; @@ -307,9 +307,11 @@ export class ListKeyManager { updateActiveItem(item: any): void { const itemArray = this._getItemsArray(); const index = typeof item === 'number' ? item : itemArray.indexOf(item); + const activeItem = itemArray[index]; + // Explicitly check for `null` and `undefined` because other falsy values are valid. + this._activeItem = activeItem == null ? null : activeItem; this._activeItemIndex = index; - this._activeItem = itemArray[index]; } /**