Home > OS >  keyup.enter/space event triggers multiple times on "@fortawesome/angular-fontawesome" icon
keyup.enter/space event triggers multiple times on "@fortawesome/angular-fontawesome" icon

Time:01-19

In my angular 6 application, there is fort awesome icon as below:

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

in .ts file, it opens a NgbModal modal window for deletion confirmation, and if a user presses 'yes' or 'no' button, it is aimed to delete the selected resource asynchronously, However since the focus from the trash icon is not moving it keeps popping up the modal window again and again on 'enter' or 'space' keys, however, it is working well on Click event through the mouse.

.ts file code

public onDeleteIconClick() {
        
        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) => { }
        );

    }

I believe that is because the focus is not moving from the thrash icon, did any encounter a similar issue?

Please note that keyup.enter, keyup.enter events are targeted for accessibility purposes.

Edit***************

Here is the stackblitz, wherein once u click on the trash icon and when it opens up the modal window, click on cancel using enter key of the keyboard, please notice that the modal window will keep appearing.

CodePudding user response:

The best solution (as suggested in Andy's comment) is to use a <button> and remove keybord bindings at all:

<button type="button" (click)="onDeleteIconClick()">
   <fa-icon [icon]="trashIcon"  tabindex="0">
   </fa-icon>
</button>

If for some reason you want to stick with your current template, you could pass the event object to onDeleteIconClick() and remove the focus from within the function:

// HTML
<fa-icon [icon]="trashIcon"  tabindex="0"
     (click)="onDeleteIconClick($event)"  
     (keyup.enter)="onDeleteIconClick($event)"  
     (keyup.Space)="onDeleteIconClick($event)">
</fa-icon>

// TS
onDeleteIconClick(ev) {
   ev.currentTarget.blur();      
   // ...
}
  • Related