首页 > 解决方案 > Angular Focusout 事件无法与表一起正常工作

问题描述

我有一张桌子。每一行都有像和这样的html元素。我想要做的是在我关注当前行之后触发一个事件()。但它不能正常工作,每当我关注当前行的任何列时它都会触发。为了解决事件,我创建了一个名为并使用如下的指令inputspanfocusoutfocus-out-directive

<tr *ngFor="let item of list"  focus-out-directive>

您可以在此链接中看到我正在处理的完整代码

标签: javascriptangulartypescript

解决方案


如果将focusout属性放在 a 上,它也会被子元素tr触发。input解决此问题的最佳方法是在指令中包含一个包含最后一个焦点单元格的行索引的属性。

event.target给你当前input元素,上面的两个父tr元素是你可以用来获取当前行索引的元素。

export class FocusOutDirective {
        @Output() onFocusOut: EventEmitter<boolean> = new EventEmitter<false>();
        lastFocusedCellRowIndex: number = -1;
    
        @HostListener("focusout", ["$event"])
        public onListenerTriggered(event: any): void {
            let currentFocusedRowIndex = event.target.parentNode.parentNode.rowIndex;
            
            if(this.lastFocusedCellRowIndex != currentFocusedRowIndex){
                this.lastFocusedCellRowIndex = currentFocusedRowIndex;
                this.onFocusOut.emit(true);
                console.log('focus out of row');
            }
        }
    }


推荐阅读