diff --git a/src/lib/core/a11y/list-key-manager.spec.ts b/src/lib/core/a11y/list-key-manager.spec.ts index 918f9c049bf5..317c2690ac03 100644 --- a/src/lib/core/a11y/list-key-manager.spec.ts +++ b/src/lib/core/a11y/list-key-manager.spec.ts @@ -15,15 +15,23 @@ class FakeQueryList extends QueryList { } } -const DOWN_ARROW_EVENT = { keyCode: DOWN_ARROW } as KeyboardEvent; -const UP_ARROW_EVENT = { keyCode: UP_ARROW } as KeyboardEvent; -const TAB_EVENT = { keyCode: TAB } as KeyboardEvent; -const HOME_EVENT = { keyCode: HOME } as KeyboardEvent; -const END_EVENT = { keyCode: END } as KeyboardEvent; +class FakeEvent { + defaultPrevented: boolean = false; + constructor(public keyCode: number) {} + preventDefault() { + this.defaultPrevented = true; + } +} + describe('ListKeyManager', () => { let keyManager: ListKeyManager; let itemList: FakeQueryList; + let DOWN_ARROW_EVENT: KeyboardEvent; + let UP_ARROW_EVENT: KeyboardEvent; + let TAB_EVENT: KeyboardEvent; + let HOME_EVENT: KeyboardEvent; + let END_EVENT: KeyboardEvent; beforeEach(() => { itemList = new FakeQueryList(); @@ -35,6 +43,12 @@ describe('ListKeyManager', () => { keyManager = new ListKeyManager(itemList); + DOWN_ARROW_EVENT = new FakeEvent(DOWN_ARROW) as KeyboardEvent; + UP_ARROW_EVENT = new FakeEvent(UP_ARROW) as KeyboardEvent; + TAB_EVENT = new FakeEvent(TAB) as KeyboardEvent; + HOME_EVENT = new FakeEvent(HOME) as KeyboardEvent; + END_EVENT = new FakeEvent(END) as KeyboardEvent; + // first item is already focused keyManager.focusFirstItem(); @@ -166,6 +180,14 @@ describe('ListKeyManager', () => { expect(tabOutEmitted).toBe(true); }); + it('should prevent the default keyboard action', () => { + expect(DOWN_ARROW_EVENT.defaultPrevented).toBe(false); + + keyManager.onKeydown(DOWN_ARROW_EVENT); + + expect(DOWN_ARROW_EVENT.defaultPrevented).toBe(true); + }); + }); describe('programmatic focus', () => { diff --git a/src/lib/core/a11y/list-key-manager.ts b/src/lib/core/a11y/list-key-manager.ts index 8e447ff0c327..1c064db0574d 100644 --- a/src/lib/core/a11y/list-key-manager.ts +++ b/src/lib/core/a11y/list-key-manager.ts @@ -42,15 +42,19 @@ export class ListKeyManager { onKeydown(event: KeyboardEvent): void { switch (event.keyCode) { case DOWN_ARROW: + event.preventDefault(); this.focusNextItem(); break; case UP_ARROW: + event.preventDefault(); this.focusPreviousItem(); break; case HOME: + event.preventDefault(); this.focusFirstItem(); break; case END: + event.preventDefault(); this.focusLastItem(); break; case TAB: