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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A focus trap works by intercepting Tab and wrapping focus from the last element back to the first and vice versa.
- 2Restoring the previously focused element on teardown preserves the user's place after a dialog closes.
- 3Querying focusable elements live keeps the trap correct even as the DOM inside the host changes.
Related explainers
typescript
type AsyncFn<A extends unknown[], R> = (...args: A) => Promise<R>; interface MemoizeOptions<A extends unknown[]> { keyFn?: (...args: A) => string;
Memoizing async functions with TTL in TypeScript
memoization
generics
promises
Advanced
8 steps
typescript
import { Injectable, Scope, Inject } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express';
Request-scoped context service in NestJS
dependency-injection
request-scope
immutability
Intermediate
8 steps
javascript
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from "react"; export function Dropdown({ label, children }) { const [open, setOpen] = useState(false);
Closing a dropdown on outside click in React
outside-click
event-listeners
cleanup
Intermediate
8 steps
typescript
interface PollOptions<T> { intervalMs?: number; timeoutMs?: number; signal?: AbortSignal;
A cancellable polling helper in TypeScript
polling
async-await
abortsignal
Intermediate
9 steps
typescript
type Ok<T> = { ok: true; value: T }; type Err<E> = { ok: false; error: E }; export type Result<T, E> = Ok<T> | Err<E>;
A Result type for typed error handling
discriminated-union
error-handling
type-guards
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-focus-trap-directive-in-angular-explained-typescript-91ad/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.