Han Che
Han Che

Reputation: 8519

angular material autocomplete - how to prevent keyboard enter to select an option in the suggestion panel

I want to be able to implement a custom enter behaviour for material autocomplete when hitting the enter key while having an active option selected via arrowkeys.

Currently I have a directive (preventEnterDirective) binded to the same input element where matAutocomplete sits. And I'm preventing the default when keydown.enter emits. But the selection is already being done, when keydown.enter emits.

<input preventEnterDirective type="text" [matAutocomplete]="auto" [formControl]="searchInputControl" type="text">
@HostListener('keydown.enter', ['$event']) public onEnter(evt: KeyboardEvent) {
    evt.preventDefault();
}

EDIT

Here is a stackblitz repo

https://stackblitz.com/edit/angular-txehk4-sic3ej

EDIT 2

I dug a little bit deeper into the source code of angular's autocomplete directive and found this on line 379 in autocomplete-trigger.ts

  _handleKeydown(event: KeyboardEvent): void {
    const keyCode = event.keyCode;
    ...
    if (this.activeOption && keyCode === ENTER && this.panelOpen) {
      this.activeOption._selectViaInteraction();
      this._resetActiveItem();
      event.preventDefault();
    } else if (this.autocomplete) {
      const prevActiveItem = this.autocomplete._keyManager.activeItem;
      const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;

      if (this.panelOpen || keyCode === TAB) {
        this.autocomplete._keyManager.onKeydown(event);
      } else if (isArrowKey && this._canOpen()) {
        this.openPanel();
      }

      if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
        this._scrollToOption();
      }
    }
  }

so basically I have two different directives which binds to an input element and have listeners with preventDefault() called.

Upvotes: 4

Views: 6043

Answers (1)

Tilak Dewangan
Tilak Dewangan

Reputation: 361

Please remove your code autoActiveFirstOption="true" from your stackblitz code then it will surely work.

Upvotes: 2

Related Questions