Angular Material 2自动完成,mat-option元素不会触发keyup事件

Pra*_*lia 3 javascript events keyup angular-material angular

我正在寻找一种方法来确定何时单击或使用回车键选择mat-option内部mat-autocomplete.

click事件绑定如预期,但作品keyup.enter甚至只是keyup事件不起作用.

这是库中的错误还是我做错了什么?

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

这是一个实例 - https://angular-3okq5u.stackblitz.io

更新:请提及是否有更好的方法来处理<mat-option>元素级别的选项选择.

Pri*_*Raj 11

如果要在选项更改时触发函数,请在选项中使用onSelectionChange事件.如果您使用键盘选择您要在此处尝试实现的自动完成选项,它也会触发.

<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>
Run Code Online (Sandbox Code Playgroud)

更新

每次更改选项时,onSelectionChange事件都会触发两次,因为Angular材质中存在问题.还要解决这个问题,你应该在执行函数之前检查事件.

 onEnter(evt: any){
    if (evt.source.selected) {
    alert("hello ");
    }
  }
Run Code Online (Sandbox Code Playgroud)

工作演示