javascript Angular Material 2 自动完成,mat-option 元素不会触发 keyup 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47629024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular Material 2 Autocomplete, mat-option element doesn't trigger keyup event
提问by Praveen Puglia
I am looking for a way to figure out when an mat-optioninside the mat-autocompletewas either clicked or was selected using the enter key.
我正在寻找一种方法来确定何时单击或使用 Enter 键选择了mat-option内部mat-autocomplete。
The clickevent binding works as expected but the keyup.enteror even just the keyupevent doesn't work.
该click事件绑定如预期,但作品keyup.enter甚至只是keyup事件不起作用。
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
这是一个活生生的例子 - 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.
更新:请提及是否有更好的方法来处理<mat-option>元素级别的选项选择。
回答by Prithivi Raj
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.
如果要在选项更改时触发功能,请在选项中使用 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>
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.
每当您更改选项时,onSelectionChange 事件都会触发两次,这是因为Angular material 中存在的问题。还给出了解决此问题的方法,即您应该在函数内部执行任何操作之前检查事件。
onEnter(evt: any){
if (evt.source.selected) {
alert("hello ");
}
}

