← Back to Angular, page 4

angular-0077 · Medium mid

How do you build an accessible popup with the Angular CDK Overlay, a focus trap and the LiveAnnouncer?

The CDK Overlay renders content above the page in a positioned container. A position strategy anchors it to a trigger, a scroll strategy decides what happens on scroll, and a backdrop can close it on outside clicks. Add cdkTrapFocus to keep keyboard focus inside, close on Escape, return focus to the trigger, and announce changes with LiveAnnouncer.

Full answer

The Component Dev Kit (CDK) holds the behaviour behind Angular Material without the styling. The Overlay module is the base for menus, tooltips, dialogs, and autocomplete panels.

Parts:

  • Overlay.create(config) returns an OverlayRef. Config includes positionStrategy, scrollStrategy, hasBackdrop, and panel class names.
  • Position strategy: overlay.position().flexibleConnectedTo(triggerElement).withPositions([...]) anchors the panel to a trigger and flips it when there is no room. .global().centerHorizontally() is for dialogs.
  • Scroll strategy: reposition() follows the trigger, block() stops page scroll, and close() closes on scroll.
  • Portals: TemplatePortal or ComponentPortal is the content you attach with overlayRef.attach(portal).
  • overlayRef.backdropClick(), keydownEvents(), and outsidePointerEvents() are streams for closing.
  • Always call overlayRef.dispose(), or the panel and its listeners stay in the page.

Accessibility pieces from @angular/cdk/a11y:

  • cdkTrapFocus keeps Tab and Shift+Tab inside the popup. cdkTrapFocusAutoCapture moves focus into it when it opens and restores focus to the previously focused element (the trigger) when it closes.
  • LiveAnnouncer.announce('Menu opened') writes to a hidden live region that screen readers read.
  • Give the panel a role (dialog or menu), a label, and close it on Escape.

For a real product, use the ready-made Dialog (from the CDK) or MatDialog, and use the Overlay directly for custom widgets. Test with a keyboard first.

For modals, set aria-modal="true", and make the page behind inert if possible.

typescript
import { A11yModule, LiveAnnouncer } from '@angular/cdk/a11y';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { Component, OnDestroy, TemplateRef, ViewContainerRef, inject, viewChild } from '@angular/core';

@Component({
  selector: 'app-help-popover',
  imports: [A11yModule],
  template: `
    <button #trigger type="button" aria-haspopup="dialog" (click)="open(trigger)">Help</button>

    <ng-template #panel>
      <div class="panel" role="dialog" aria-label="Help" cdkTrapFocus cdkTrapFocusAutoCapture>
        <p>Use your roll number to log in.</p>
        <button type="button" (click)="close()">Close</button>
      </div>
    </ng-template>
  `,
  styles: `
    .panel { background: white; border: 1px solid #888; padding: 12px; border-radius: 6px; }
  `,
})
export class HelpPopoverComponent implements OnDestroy {
  private readonly overlay = inject(Overlay);
  private readonly viewContainer = inject(ViewContainerRef);
  private readonly announcer = inject(LiveAnnouncer);
  private readonly panel = viewChild.required<TemplateRef<unknown>>('panel');
  private overlayRef?: OverlayRef;

  open(trigger: HTMLElement): void {
    if (this.overlayRef?.hasAttached()) {
      return;
    }
    this.overlayRef = this.overlay.create({
      positionStrategy: this.overlay
        .position()
        .flexibleConnectedTo(trigger)
        .withPositions([
          { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top' },
          { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom' },
        ]),
      scrollStrategy: this.overlay.scrollStrategies.reposition(),
      hasBackdrop: true,
      backdropClass: 'cdk-overlay-transparent-backdrop',
    });

    this.overlayRef.backdropClick().subscribe(() => this.close());
    this.overlayRef.keydownEvents().subscribe((e) => {
      if (e.key === 'Escape') {
        this.close();
      }
    });

    this.overlayRef.attach(new TemplatePortal(this.panel(), this.viewContainer));
    void this.announcer.announce('Help opened');
  }

  close(): void {
    this.overlayRef?.dispose();
    this.overlayRef = undefined;
    void this.announcer.announce('Help closed');
  }

  ngOnDestroy(): void {
    this.overlayRef?.dispose();
  }
}

Angular 20.3 with CDK 20.2, strict template check passes. Press Escape or click outside to close.

Key points

  • `Overlay.create` plus a position strategy, a scroll strategy, and a portal builds a popup.
  • `cdkTrapFocus` with auto capture handles focus in and out. Close on Escape.
  • `LiveAnnouncer` tells screen readers about changes.
  • Always `dispose()` the overlay.

Common mistakes

  • Not disposing the overlay, leaving listeners and DOM nodes behind.
  • Opening a popup without moving focus into it, or not returning focus afterwards.
  • Positioning with absolute CSS values that break when the page scrolls.

Follow-ups

  • How does `flexibleConnectedTo` choose among positions?
  • When would you use `ComponentPortal` instead of `TemplatePortal`?
  • How do you make the rest of the page inert while a modal is open?

Tips

  • Say you would use the CDK or Material Dialog for ordinary dialogs, and Overlay for custom widgets.
  • Mention focus return. It is the most commonly missed detail.
  • Name `dispose()` and cleanup.

Evaluation rubric

  • Explains position, scroll, backdrop, and portal concepts.
  • Uses cdkTrapFocus and LiveAnnouncer correctly.
  • Closes and cleans up properly.