【发布时间】: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!!
}
}
【问题讨论】: