首页 > 解决方案 > 无法在 mat-option 的自定义指令中侦听 keydown 事件

问题描述

我正在尝试将指令绑定到一些 mat-options 以获取它们的 keydown 事件。该指令似乎正在初始化,但似乎没有响应按键事件。知道为什么 onKeydown 函数没有触发吗?

指示

    import { Directive, ElementRef, HostListener } from '@angular/core';

    @Directive({
      selector: '[appSelectTab]'
    })

    export class SelectTabDirective {

    constructor(private el: ElementRef) { console.log('init') }

    @HostListener('document:keydown', ['$event']) onKeydownHandler(event: 
    KeyboardEvent) {
    if(event.code.toLowerCase() == "tab"){
       //tab performed on the first option in the select list for example
       //this.el.nativeElement do something to or with me.
    }
    //this doesn't work because the listener is fired for all of the mat-options
}

标记:

<mat-option appSelectTab *ngFor="let schedule of maintenanceSchedule" [value]="schedule">
    {{ schedule }}
</mat-option>

此外,我需要执行 keydown 事件的特定 mat-option。

标签: angularangular-material

解决方案


尝试这个。

100% 工作:https ://stackblitz.com/edit/material-select-change-event-tyhtgk

 import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appSelectTab]'
})
export class SelectTabDirective {
mouseThere=false;
constructor(private el: ElementRef) { console.log('init in directive') }
@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
    if(this.mouseThere && event.code.toLowerCase() == "tab"){
      // console.log(event)
    // console.log(this.el)
    let wholeValue=this.el.nativeElement.getAttribute('ng-reflect-value').split("-");
    let value=wholeValue[0];
    let i=parseInt(wholeValue[1]);
    console.log(`You pressed tab on ${i+1} option whose value is ${value}`)

    }
}
@HostListener('mouseenter', ['$event']) mouseEnterHandler(event: MouseEvent) {
  console.log("Mouse Enter")
   // console.log(event)
    this.mouseThere=true;
}
@HostListener('mouseleave', ['$event']) mouseLeaveHandler(event: MouseEvent) {
    //console.log("Mouse leave")
    //console.log(event)
   this.mouseThere=false;
}

}

推荐阅读