Search code examples
bootstrap-modalkeypressng-bootstrapstoppropagation

How to avoid key binding propagation inside ng-bootstrap ngbModal component?


In keeping the page in compliance with ADA, we're required to being able to open the ng-bootstrap (ngbModal) modal popup by either clicking/space/enter on the "OPEN" button.

<div (keyup.enter)="openModal($event)" (keyup.space)="openModal($event) (click)="openModal($event)">Open Modal</div> 

Inside the modal page:

<button>Close</button>

Pressing enter on the close button closes the modal, goes back to the calling div element and re-executes to ENTER key and re-opens the modal one more time. I've tried stoppropagation, return false, cancelbubble inside the openModal function and inside the modal itself to no avail, the bound ENTER key keeps bubbling up/down the two pages.


Solution

  • I was able to solve it by the following implementation inside modal:

     @HostListener("document:keydown", ["$event"]) onKeydownHandler(
        event: KeyboardEvent
      ) {
        if(event.key === "Enter"){
          event.preventDefault();
          event.stopImmediatePropagation();
        }
      }