Skip to content

Commit 49fa9c8

Browse files
committed
fix(autocomplete): don't block default arrow keys when using modifiers
Currently we hijack all up/down arrow key events, however this interferes with keyboard shortcuts such as shift + up arrow for marking all of the text. These changes stop intercepting the arrow keys, if they're used with a modifier. These changes also fix an issue where all the mocked out key events had the `metaKey` set to `true` on some browsers.
1 parent 09dc459 commit 49fa9c8

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/material/autocomplete/autocomplete-trigger.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -412,15 +412,16 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn
412412
event.preventDefault();
413413
} else if (this.autocomplete) {
414414
const prevActiveItem = this.autocomplete._keyManager.activeItem;
415-
const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
415+
const isVerticalArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
416+
const hasModifier = event.ctrlKey || event.altKey || event.metaKey || event.shiftKey;
416417

417-
if (this.panelOpen || keyCode === TAB) {
418+
if ((isVerticalArrowKey && !hasModifier) || keyCode === TAB) {
418419
this.autocomplete._keyManager.onKeydown(event);
419-
} else if (isArrowKey && this._canOpen()) {
420+
} else if (isVerticalArrowKey && this._canOpen()) {
420421
this.openPanel();
421422
}
422423

423-
if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
424+
if (isVerticalArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
424425
this._scrollToOption();
425426
}
426427
}

src/material/autocomplete/autocomplete.spec.ts

+12
Original file line numberDiff line numberDiff line change
@@ -1250,6 +1250,18 @@ describe('MatAutocomplete', () => {
12501250
expect(!!trigger.activeOption).toBe(false, 'Expected no active options.');
12511251
}));
12521252

1253+
it('should not prevent the default action when a modifier key is pressed', () => {
1254+
['metaKey', 'ctrlKey', 'altKey', 'shiftKey'].forEach(name => {
1255+
const event = createKeyboardEvent('keydown', DOWN_ARROW);
1256+
Object.defineProperty(event, name, {get: () => true});
1257+
1258+
fixture.componentInstance.trigger._handleKeydown(event);
1259+
fixture.detectChanges();
1260+
1261+
expect(event.defaultPrevented).toBe(false, `Expected autocompete not to block ${name} key`);
1262+
});
1263+
});
1264+
12531265
});
12541266

12551267
describe('option groups', () => {

0 commit comments

Comments
 (0)