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

typescript
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, timer, throwError } from 'rxjs';
import { switchMap, takeWhile, filter, take, catchError } from 'rxjs/operators';

Polling a job until it finishes in Angular

rxjs polling observables
Intermediate 7 steps
javascript
import { useState } from 'react';
 
function StarRating({ value = 0, max = 5, onChange, size = 24 }) {
  const [hovered, setHovered] = useState(null);

Building an accessible star rating in React

controlled-component accessibility state-management
Intermediate 8 steps
typescript
type Flatten = Record<string, unknown>;
 
function isPlainObject(value: unknown): value is Record<string, unknown> {
  return (

Flattening nested objects into dotted keys

recursion reduce type-guards
Intermediate 7 steps
typescript
import { Injectable, signal, computed, effect, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
 
export type Theme = 'light' | 'dark';

A signal-based theme service in Angular

signals reactivity dependency-injection
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, distinctUntilChanged, scan } from 'rxjs/operators';

Tracking upload progress in Angular

rxjs http-events state-reduction
Intermediate 8 steps
typescript
import { Component, HostBinding, Input } from '@angular/core';
 
type ProgressVariant = 'success' | 'warning' | 'danger';
 

A CSS-driven progress ring in Angular

host-bindings css-custom-properties input-setters
Intermediate 8 steps

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