Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Han Che Avatar asked Oct 23 '25 19:10

Han Che


1 Answers

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

like image 60
Tilak Dewangan Avatar answered Oct 26 '25 09:10

Tilak Dewangan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!