当我使用 2 个单独的指令时,Angular 指令只有一个实例有效

Angulare Directive only one instance works, when i use 2 sepate directives

我有一个针对 arrow uparrow down 需求的指令。当我复制指令实例之一并将其分页时,只有第二个有效,但第一个无效。

如何解决这个问题?请关注第一个元素的第二部分“绿色”彩色部分,并进行 up and down 箭头移动。

directive.ts:

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

@Directive({
  selector: '[appFocuser]',
})
export class AutoFocusDirective implements AfterViewInit {
  focusableArray = [];
  parent = null;
  count = 0;
  currentFocus: HTMLElement;
  constructor(private el: ElementRef) {}

  @HostListener('document:keyup', ['$event']) onKeyup = ($event) => {
    if ($event.code === 'ArrowDown') {
      if (this.count >= this.focusableArray.length - 1) {
        this.count = 0;
        this.focusableArray[this.count].focus();
        return;
      }
      this.count++;
      this.focusableArray[this.count].focus();
    }
    if ($event.code === 'ArrowUp') {
      if (this.count == 0) {
        this.count = this.focusableArray.length - 1;
        this.focusableArray[this.count].focus();
        return;
      }
      this.count--;
      this.focusableArray[this.count].focus();
    }
  };

  ngAfterViewInit() {
    this.parent = this.el.nativeElement;
    this.focusableArray = Array.from(
      this.parent.querySelectorAll(`[data-focus=true]`)
    );
    if (this.focusableArray.length) {
      this.currentFocus = this.focusableArray[this.count];
      this.currentFocus.focus();
    }
  }
}

Live Demo

事实上,这两个实例都有效。相继。这里

  @HostListener('document:keyup', ['$event']) onKeyup = ($event) => {

您正在监听整个文档的 keyup 事件。 AutoFocusDirective 的每个实例都会捕获它,所有处理程序都会执行,大概是按照指令初始化的顺序(可能)。第一个将焦点分配到某处(您甚至可以看到它的闪光)。然后第二个也一样,抢了焦点。

一个解决方案是不监听 document:keyup,而是监听 keyup

这是因为页面中只能聚焦一个元素。您必须将两个 section 部分放在另一个元素中,并为该元素提供 appFocuser 指令。

Live Demo