Search code examples
javascriptangulareventsangular-materialkeyup

Angular Material 2 Autocomplete, mat-option element doesn't trigger keyup event


I am looking for a way to figure out when an mat-option inside the mat-autocomplete was either clicked or was selected using the enter key.

The click event binding works as expected but the keyup.enter or even just the keyup event doesn't work.

Is this a bug in the library or I am doing something wrong?

<mat-option (click)="onEnter()" (keyup.enter)="onEnter()" *ngFor="let state of filteredStates | async" [value]="state.name">

Here's a live example - https://angular-3okq5u.stackblitz.io

Update: Please mention if there's a better way to handle the selection of an option at the <mat-option> element level.


Solution

  • Use onSelectionChange event in options if you want to trigger a function on option change. it will also trigger if you use keyboard to select the auto-complete option which you are trying to achieve here.

    <input (keyup.enter)="onEnter($event)" matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
        <mat-autocomplete  #auto="matAutocomplete">
          <mat-option  (onSelectionChange)="onEnter($event)" (click)="onEnter()"  *ngFor="let state of filteredStates | async" [value]="state.name">
            <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
            <span>{{ state.name }}</span> |
            <small>Population: {{state.population}}</small>
          </mat-option>
        </mat-autocomplete>
    

    Update

    onSelectionChange event is triggering twice whenever you change the option and it's because of the existing issue in Angular material. Work around for the issue is also given that you should check the event before doing anything inside the function.

     onEnter(evt: any){
        if (evt.source.selected) {
        alert("hello ");
        }
      }
    

    Working demo