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 { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 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