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

时间:2017-12-04 08:11:14

标签: javascript angular events angular-material keyup

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

click事件绑定按预期工作,但keyup.enter甚至keyup事件都不起作用。

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

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

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

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

2 个答案:

答案 0 :(得分:9)

如果要在选项更改时触发功能,请在选项中使用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>

<强>更新

每次更改选项时,

onSelectionChange事件都会触发两次,因为existing issue in Angular material。解决这个问题的另一个方法是,你应该在执行函数之前检查事件。

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

Working demo

答案 1 :(得分:0)

我用过:

<mat-option (onSelectionChange)="choose(item)" 
            *ngFor="let item of keyWord" value="{{item}}"> {{item}} </mat-option>