Невозможно прослушать событие keydown внутри пользовательской директивы для mat-option - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь связать директиву с некоторыми опциями mat для получения событий 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>

Кроме того, мне нужна опция c mat-option что событие keydown было выполнено.

Ответы [ 2 ]

1 голос
/ 26 марта 2020

Попробуйте это.

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;
}

}
0 голосов
/ 26 марта 2020

я думаю, что вы минус schedule.(option) пример [value]="food.value">. *ngfor в графике обслуживания. Какая ошибка произошла? или ничего не случилось

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...