【问题标题】:Angular Directive - focus back to first attribute elementAngular Directive - 重新关注第一个属性元素
【发布时间】:2021-10-27 12:56:46
【问题描述】:

我正在为焦点设置添加指令。在focus-able 元素的情况下,它的数据将被标识为[attr.focus]="true" 例如我有2 个添加了属性的按钮。

在指令加载时,第一个元素聚焦。但是当用户blurs最后一个元素时,我想带他回到第一个元素。直到我从元素中输入。我的指令不适用于它。我和孩子一起尝试addEventListener

如何处理?

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

@Directive({
  selector: '[autoFocus]'
})
export class AutofocusDirective implements AfterContentInit {
  @Input() public autoFocus: boolean;
  selector = `[focus="true"]`;
  dealy: number;

  public constructor(private readonly el: ElementRef) {
    this.dealy = 100;
  }

  public ngAfterContentInit() {
    setTimeout(() => {
      const focus = this.el.nativeElement.querySelectorAll(this.selector);
      const first = focus[0];
      const last = focus[focus.length - 1];
      if (first) {
        first.focus();
      }

      last.nativeElement.addEventListner('blur', () => {
        first.focus();
      });
    }, this.dealy); //not works!!
  }
}

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    我建议记录焦点元素,看看这是否真的找到了两个按钮。

    const focus = this.el.nativeElement.querySelectorAll(this.selector);
    console.log({focus});
    

    您写道,您将属性应用于两个按钮,但由于您使用this.el.nativeElement.querySelectorAll 搜索具有该属性的元素下方的元素,我建议将其替换为document.querySelectorAll

    另一种解决方案可能是区分根指令,即在另一个指令中搜索元素。

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 1970-01-01
      • 2020-12-24
      • 2018-07-03
      • 2013-04-30
      • 1970-01-01
      • 2015-06-07
      • 2018-06-27
      • 2017-12-18
      相关资源
      最近更新 更多