angular - 无法在 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。
解决方案
尝试这个。
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;
}
}
推荐阅读
- php - Hash::check in Laravel 5 不起作用,总是返回 false?
- oracle - SSIS 未与 OraOLEDB.Oracle.1 提供程序并行运行
- git - Jenkins - BitBucket git push:无法读取没有此类设备或地址的密码
- android - Ui Automator 截图
- python - 使用 keras 时在推理之间空闲 GPU
- vue.js - 将元素拖放到同一列表中的列表中。vue-smooth-dnd
- javascript - 当另一个元素处于活动状态时更改元素的样式
- mysql - 仅当与 Eloquent 中的 ID 匹配时才选择特定列
- python - 表单中的数据未写入 sqlite DB
- sqlite - 在 Mac 上编译 sqilte3