You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 6中FontAwesome图标keyup.enter/space事件多次触发问题

解决Angular 6中FontAwesome图标触发NgbModal重复弹出的问题

你遇到的问题主要有两个原因:

  1. 模板中(keyup.Space)的事件绑定少了括号,导致函数引用传递异常;
  2. 触发键盘事件后焦点仍停留在图标上,模态框关闭后焦点回到图标,再次触发事件导致模态框重复弹出。

下面是具体的修复方案:

方案一:修正事件绑定并主动移除焦点

1. 修复模板中的键盘事件

把(keyup.Space)="onDeleteIconClick"改成(keyup.Space)="onDeleteIconClick()",确保事件触发时正确调用函数:

<div>
  <fa-icon #deleteIcon 
           [icon]="trashIcon" 
           class="custom-trash-icon" 
           tabindex="0"
           (click)="onDeleteIconClick()"
           (keyup.enter)="onDeleteIconClick()"
           (keyup.Space)="onDeleteIconClick()">
  </fa-icon>
</div>

2. 在组件中让图标失去焦点

通过ViewChild获取图标元素,在打开模态框前调用blur()让它失去焦点:

首先在组件类中引入并声明ViewChild:

import { Component, ViewChild, ElementRef } from '@angular/core';
// 其他必要的导入...

@Component({
  // 组件元数据...
})
export class YourComponent {
  @ViewChild('deleteIcon') deleteIcon: ElementRef;

  // 其他代码...

  public onDeleteIconClick() {
    // 让图标失去焦点,避免模态框关闭后焦点返回触发重复事件
    this.deleteIcon.nativeElement.blur();

    const modalRef = this._modalService.open(DeleteComponent, {
      backdrop: "static",
      windowClass: "custom-modal",
      keyboard: true,
      centered: true,
    });
    modalRef.componentInstance.confirmationText = `Do you want to delete the resource?`;
    modalRef.result.then(
      (result) => {
        if (result && result.toLowerCase() === "yes") {
          this.deleteResource.emit();
        }
      },
      (reason) => { }
    );
  }
}

方案二:改用keydown事件并阻止默认行为

如果使用keyup时存在按键按住导致多次触发的情况,可以改用keydown事件,同时阻止默认行为:

1. 修改模板事件绑定

<div>
  <fa-icon #deleteIcon 
           [icon]="trashIcon" 
           class="custom-trash-icon" 
           tabindex="0"
           (click)="onDeleteIconClick()"
           (keydown.enter)="handleDeleteKeyEvent($event)"
           (keydown.space)="handleDeleteKeyEvent($event)">
  </fa-icon>
</div>

2. 添加键盘事件处理函数

handleDeleteKeyEvent(event: KeyboardEvent) {
  // 阻止事件的默认行为,避免重复触发
  event.preventDefault();
  // 让图标失去焦点
  this.deleteIcon.nativeElement.blur();
  // 执行删除逻辑
  this.onDeleteIconClick();
}

这样既可以避免按键持续按下导致的多次触发,也能确保焦点不会停留在图标上引发重复弹窗。

内容的提问来源于stack exchange,提问作者Dev Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:15:25