Search code examples
javascripthtmlcssangularngx-bootstrap

How to stop TAB key event from firing when a modal is open


When the modal is showing, how can I disable key events like TAB? I have multiple buttons and fields in a form on the page that can be selected (focused) by tabbing. I want to disable that when the modal is showing. The application uses Angular and the modal is in a child component.

<button tabindex="0">Button1</button>
<button tabindex="0">Button2</button>
<form>...</form>

<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">...</div>
  </div>
</div>

Solution

  • I'd suggest something like this - use Renderer2 and listen for a keydown event and filter events by keyCode. Then on modal hide remove that listener.

    onShow() {
       this.removeTabKeyListener = this.renderer.listen('document', 'keydown', (event) => {
          if (event.keyCode === 9) { 
            event.preventDefault();
          }
        });
    }
    
    onHide() {
      this.removeTabKeyListener();
    }
    

    A little example - http://plnkr.co/edit/LdpmCpgapPbrA26fGO9U?p=preview