How-to trap focus to an HTML element in Angular

How-to trap focus to an HTML element in Angular

Are you struggling to trap focus to an HTML element in Angular? Here's a quick guide on how you should do it.

If you’ve ever worked with a large corporation or a fortune 500, you’d know how picky they can be when it comes to UX. We were recently doing an integration with a partner and a requirement came up where — for accessibility reasons — they wanted us to trap focus to an open popup until it was closed. There already are a few articles out there on how-to do this, this article just builds upon them, showing how-to do this in Angular as well as adding support for Angular components with shadow DOM.

Let’s get started, shall we?

  1. Open console in the root of your angular project.
  2. Create a new directive by executing: ng g d trap-focus.
  3. Copy the following code into your newly created “trap-focus.directive.ts” file.

4.‎‎‏‏‎ ‎‏‏‎ ‎Now, in the component where you want to trap focus, add the trapFocus attribute to the HTML element. 5.‏‎ ‎‏‏‎ ‎Voila! That’s it. You should be able to trap focus now.

How does it work?

Since you’ve made it this far, I’m assuming you’re eager to learn how does it work? It is quite simple actually. When you add the trapFocus attribute, the following happens:

  • An event listeners, for the keydown event, is attached to the HTML element.
  • On keydown, our event listener is triggered.
  • If the pressed key is not “tab”, flow breaks and nothing happens.
  • Otherwise, it gets the list of all focusable elements and determines the first and the last focusable element in the parent element.
  • If “shift + tab” were pressed and currently focused element is first focusable element, it focuses the last focusable element and prevents default behavior.
  • If “tab” was pressed and currently focused element is the last focusable element, it focuses the first focusable element and prevents default behavior.

That is it! Quite simple right?


This article is a part of my Coding series. You may find other useful articles for your daily development there as well.

If you found this helpful or enjoyed reading the article, please do the following: