typescript 54 lines · 9 steps

Building a focus-trap directive in Angular

An Angular attribute directive that keeps keyboard focus inside a host element, ideal for modals and dialogs.

Explained by highlit
1import { Directive, ElementRef, HostListener, Input, OnDestroy, OnInit } from '@angular/core';
2 
3@Directive({
4 selector: '[appTrapFocus]',
5 standalone: true,
6})
7export class TrapFocusDirective implements OnInit, OnDestroy {
8 @Input('appTrapFocus') enabled = true;
9 
10 private previouslyFocused: HTMLElement | null = null;
11 private readonly focusableSelector =
12 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
13 
14 constructor(private readonly host: ElementRef<HTMLElement>) {}
15 
16 ngOnInit(): void {
17 if (!this.enabled) return;
18 this.previouslyFocused = document.activeElement as HTMLElement | null;
19 queueMicrotask(() => this.getFocusable()[0]?.focus());
20 }
21 
22 ngOnDestroy(): void {
23 this.previouslyFocused?.focus();
24 }
25 
26 @HostListener('keydown', ['$event'])
27 onKeydown(event: KeyboardEvent): void {
28 if (!this.enabled || event.key !== 'Tab') return;
29 
30 const focusable = this.getFocusable();
31 if (focusable.length === 0) {
32 event.preventDefault();
33 return;
34 }
35 
36 const first = focusable[0];
37 const last = focusable[focusable.length - 1];
38 const active = document.activeElement;
39 
40 if (event.shiftKey && active === first) {
41 event.preventDefault();
42 last.focus();
43 } else if (!event.shiftKey && active === last) {
44 event.preventDefault();
45 first.focus();
46 }
47 }
48 
49 private getFocusable(): HTMLElement[] {
50 return Array.from(
51 this.host.nativeElement.querySelectorAll<HTMLElement>(this.focusableSelector),
52 ).filter((el) => el.offsetParent !== null);
53 }
54}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A focus trap works by intercepting Tab and wrapping focus from the last element back to the first and vice versa.
  2. 2Restoring the previously focused element on teardown preserves the user's place after a dialog closes.
  3. 3Querying focusable elements live keeps the trap correct even as the DOM inside the host changes.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a focus-trap directive in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code