Skip to content

fix(a11y): inconsistent runtime value for ListKeyManager.activeItem #14154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/cdk/a11y/key-manager/list-key-manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
6 changes: 4 additions & 2 deletions src/cdk/a11y/key-manager/list-key-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shif
*/
export class ListKeyManager<T extends ListKeyManagerOption> {
private _activeItemIndex = -1;
private _activeItem: T;
private _activeItem: T | null = null;
private _wrap = false;
private _letterKeyStream = new Subject<string>();
private _typeaheadSubscription = Subscription.EMPTY;
Expand Down Expand Up @@ -307,9 +307,11 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
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;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a comment like

// Explicitly check for `null` and `undefined` because other falsy values are valid.

this._activeItemIndex = index;
this._activeItem = itemArray[index];
}

/**
Expand Down