Angular course Β· Module 12: Security and Performance

Accessibility (a11y)

3 min read Β·
In this lesson5

Accessibility is like building a castle with gates for all guests:

Accessibility Basics

@Component({
  template: `
    <!-- Semantic HTML -->
    <nav aria-label="Main navigation">
      <ul>
        @for (link of navLinks; track link.path) {
          <li>
            <a [routerLink]="link.path"
               [attr.aria-current]="isActive(link.path) ? 'page' : null">
              {{ link.label }}
            </a>
          </li>
        }
      </ul>
    </nav>

    <!-- Accessible forms -->
    <form>
      <label for="samuraiName">Samurai name</label>
      <input
        id="samuraiName"
        type="text"
        [attr.aria-invalid]="nameControl.invalid"
        [attr.aria-describedby]="nameControl.invalid ? 'nameError' : null"
      >
      @if (nameControl.invalid) {
        <span id="nameError" role="alert">
          Name is required
        </span>
      }
    </form>

    <!-- Buttons with descriptions -->
    <button
      (click)="deleteSamurai()"
      [attr.aria-label]="'Delete samurai ' + samurai.name">
      <mat-icon>delete</mat-icon>
    </button>

    <!-- Live regions for dynamic content -->
    <div aria-live="polite" class="sr-only">
      {{ statusMessage() }}
    </div>
  `
})
export class AccessibleComponent {
  // Screen reader only class
  // .sr-only { position: absolute; width: 1px; height: 1px; ... }
}

Focus Management

@Component({
  template: `
    <dialog #dialog>
      <h2>Dialog Title</h2>
      <button #closeBtn (click)="close()">Close</button>
    </dialog>
  `
})
export class DialogComponent implements AfterViewInit {
  @ViewChild('dialog') dialog!: ElementRef<HTMLDialogElement>;
  @ViewChild('closeBtn') closeBtn!: ElementRef<HTMLButtonElement>;

  private previousFocus: Element | null = null;

  open(): void {
    this.previousFocus = document.activeElement;
    this.dialog.nativeElement.showModal();
    this.closeBtn.nativeElement.focus();
  }

  close(): void {
    this.dialog.nativeElement.close();
    (this.previousFocus as HTMLElement)?.focus();
  }
}

A focus trap for the modal: cdkTrapFocus

When a modal built from plain <div> elements is open, the Tab key can carry focus out of the window onto page elements the user cannot see right now. The @angular/cdk package has a ready directive for this, cdkTrapFocus from A11yModule (@angular/cdk/a11y): add it as an attribute of the window element and Tab and Shift+Tab will cycle only through the elements inside it. Together with role="dialog", aria-modal="true" and an aria-label, a screen reader knows it is dealing with a dialog and what it is called.

import { Component } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';

@Component({
  selector: 'app-confirm-dialog',
  standalone: true,
  imports: [A11yModule],
  template: `
    <div role="dialog" aria-modal="true" aria-label="Confirmation" cdkTrapFocus cdkTrapFocusAutoCapture>
      <p>Do you really want to leave the dojo?</p>
      <button (click)="confirm()">Yes</button>
      <button (click)="cancel()">No</button>
    </div>
  `
})
export class ConfirmDialogComponent {
  confirm(): void {}
  cancel(): void {}
}

cdkTrapFocusAutoCapture moves focus into the window as soon as it opens and, when it closes, gives it back to the element that was active before.

Keyboard Navigation

@Directive({
  selector: '[appKeyboardNav]',
  standalone: true
})
export class KeyboardNavDirective {
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent): void {
    const items = this.getNavigableItems();
    const currentIndex = items.indexOf(document.activeElement as HTMLElement);

    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault();
        items[(currentIndex + 1) % items.length]?.focus();
        break;
      case 'ArrowUp':
        event.preventDefault();
        items[(currentIndex - 1 + items.length) % items.length]?.focus();
        break;
      case 'Home':
        event.preventDefault();
        items[0]?.focus();
        break;
      case 'End':
        event.preventDefault();
        items[items.length - 1]?.focus();
        break;
    }
  }

  private getNavigableItems(): HTMLElement[] {
    return Array.from(
      this.el.nativeElement.querySelectorAll('[tabindex="0"], button, a')
    );
  }
}

Accessibility Testing

# Lighthouse audit
npm install -g lighthouse
lighthouse http://localhost:4200 --only-categories=accessibility

# axe-core in tests
npm install axe-core @axe-core/playwright

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the aria-live="polite" attribute used for?

  2. 2. Why do we add aria-label to a button that contains only an icon (e.g. <mat-icon>delete</mat-icon>)?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the accessible modal with the proper ARIA attributes.

  • Horizontal ordering

    Arrange the opening navigation tag with a label for the screen reader (from the left):

  • Vertical ordering

    Order the steps of the open() method that manages focus in a dialog (top to bottom):

  • Click in order

    Build the attribute that defines the semantics of a dialog window (click in order):

  1. QuestionARIA
  2. QuestionThe aria-label attribute
  3. QuestionThe role="alert" role
  4. Coding taskPractice: Accessibility
  5. Put in orderAccessible navigation
  6. Put in orderOpening an accessible modal
  7. Click in orderBuilding the dialog role
  8. QuestionAccessibility testing
  9. VideoModule summary

Useful articles