diff --git a/src/material/autocomplete/autocomplete-trigger.ts b/src/material/autocomplete/autocomplete-trigger.ts index 2ab382278601..4e21b9f67c76 100644 --- a/src/material/autocomplete/autocomplete-trigger.ts +++ b/src/material/autocomplete/autocomplete-trigger.ts @@ -119,6 +119,7 @@ export function getMatAutocompleteMissingPanelError(): Error { '(blur)': '_onTouched()', '(input)': '_handleInput($event)', '(keydown)': '_handleKeydown($event)', + '(click)': 'openPanel()', }, exportAs: 'matAutocompleteTrigger', providers: [MAT_AUTOCOMPLETE_VALUE_ACCESSOR] @@ -270,8 +271,10 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn /** Opens the autocomplete suggestion panel. */ openPanel(): void { - this._attachOverlay(); - this._floatLabel(); + if (!this.panelOpen) { + this._attachOverlay(); + this._floatLabel(); + } } /** Closes the autocomplete suggestion panel. */ diff --git a/src/material/autocomplete/autocomplete.spec.ts b/src/material/autocomplete/autocomplete.spec.ts index 347cc48196b3..03318ba23a7b 100644 --- a/src/material/autocomplete/autocomplete.spec.ts +++ b/src/material/autocomplete/autocomplete.spec.ts @@ -516,6 +516,29 @@ describe('MatAutocomplete', () => { expect(input.getAttribute('aria-haspopup')).toBe('false'); }); + it('should close the panel when pressing escape', fakeAsync(() => { + const trigger = fixture.componentInstance.trigger; + + input.focus(); + flush(); + fixture.detectChanges(); + + expect(document.activeElement).toBe(input, 'Expected input to be focused.'); + expect(trigger.panelOpen).toBe(true, 'Expected panel to be open.'); + + trigger.closePanel(); + fixture.detectChanges(); + + expect(document.activeElement).toBe(input, 'Expected input to continue to be focused.'); + expect(trigger.panelOpen).toBe(false, 'Expected panel to be closed.'); + + input.click(); + flush(); + fixture.detectChanges(); + + expect(trigger.panelOpen).toBe(true, 'Expected panel to reopen on click.'); + })); + }); it('should not close the panel when clicking on the input', fakeAsync(() => {