Skip to main content

04 - Web Accessibility (WCAG 2.2): Guide for Angular

How to make an Angular app accessible with WCAG 2.2: compiled components, computed contrast, axe-core run and the limits of automatic tests.

What do you think about this article?

04 - Web Accessibility (WCAG 2.2): Guide for Angular
StandalonePhoto:SiddePexels

At a Glance

How to make an Angular app accessible with WCAG 2.2: compiled components, computed contrast, axe-core run and the limits of automatic tests.

A component can look perfect and not work from the keyboard

Take any accordion, the one you find in ten tutorials: a button with a click handler, one for keydown.enter and one for keydown.space that call the same function. It looks like a prudent way to support the keyboard. In reality a native <button> already generates a click when you press Enter or Space, so the action fires twice and the panel opens and closes again in the same gesture. This is standard browser behaviour; I did not verify it in a browser for this article, and I say so because it holds for the rest of the guide: where I could not run something, I write it.

Accessibility works like this, for the most part: defects are not seen by looking at the page, they are seen by using it with the keyboard or with a screen reader, or with a tool that looks for them. Here you will find the rules (WCAG 2.2) and their application in Angular 21, with the code compiled and the tools run. Where the previous version of this article (and many guides online) was wrong, the correction is explained.

Why do it, with the right sources

According to the World Health Organization (fact sheet of 7 March 2023) about 1.3 billion people, 16% of the world's population, live with a significant disability. Not all of them use the web in the same way, but the number explains why the issue is not marginal. The second reason is regulatory: the Directive (EU) 2019/882, the European Accessibility Act, applies to products placed on the market after 28 June 2025 (article 2), and article 32 provides transitional periods for services that were already using certain products.

I do not report the Italian situation here (the Stanca Law, the thresholds for private entities) because I did not verify it against a primary source while writing: if it concerns you, check the text in force and the guidance of AgID. For the same reason I do not write that "level AA is required by law": the directive refers to harmonised standards and I did not read that passage. If a contract or a standard specifies a level, that level applies; in its absence, choosing the level for your project remains a decision of yours.

WCAG 2.2 in brief: principles, levels and what has changed

WCAG is organised in four principles, summed up by the acronym POUR. Content must be perceivable, operable, understandable and robust, and each principle translates into verifiable success criteria, each with a level A, AA or AAA. For the exact criteria the source is the W3C recommendation.

  • Perceivable: text alternatives for images, captions, sufficient contrast.
  • Operable: every function available from the keyboard, enough time, visible focus, targets that are large enough.
  • Understandable: declared language, predictable behaviour, errors that are described and correctable.
  • Robust: names, roles and states exposed so that assistive technologies can interpret them.

The four entries are not ordered by importance: they are four ways in which a person can be left out. For an Angular developer the first two are played out mostly in styling and the keyboard, the last two in templates and ARIA attributes. Version 2.2 became a W3C recommendation on 5 October 2023 and adds nine criteria to those of 2.1; the only criterion removed is 4.1.1 Parsing, now obsolete. This also means that "valid HTML" is no longer, in itself, a success criterion: it remains a good practice, not a requirement.

Starting from native HTML

The rule that avoids the most errors comes from Angular's own documentation: when you write a component, reuse native elements instead of reimplementing their behaviour. A <button> is reachable with Tab, activated with Enter and Space and communicates its role to screen readers without a line of ARIA. A <div> with a click handler does none of this, and no automatic tool notices: you will see it in the test with axe further on.

An accordion that uses ARIA only where needed

The following component is the correct version of the accordion: a single click handler on the native button, aria-expanded that reflects the state, aria-controls pointing to the panel and an aria-labelledby pointing to an identifier that really exists (in the previous version the reference was to an id that was never defined). The identifiers arrive as a required input, because two instances with the same id would break the references. I compiled it in AOT mode with strictTemplates (Angular 21.2.26, exit 0); I did not run it in a browser.

accordion-item.component.ts (compiled with ngc, not run in a browser)
import { Component, input, signal } from '@angular/core';

@Component({
  selector: 'app-accordion-item',
  template: `
    <h3>
      <button
        type="button"
        [id]="id() + '-header'"
        [attr.aria-expanded]="isOpen()"
        [attr.aria-controls]="id() + '-panel'"
        (click)="toggle()"
      >
        {{ heading() }}
      </button>
    </h3>
    <div [id]="id() + '-panel'" role="region" [attr.aria-labelledby]="id() + '-header'" [hidden]="!isOpen()">
      <ng-content />
    </div>
  `,
})
export class AccordionItemComponent {
  readonly id = input.required<string>();
  readonly heading = input.required<string>();
  protected readonly isOpen = signal(false);

  protected toggle(): void {
    this.isOpen.update((v) => !v);
  }
}

The binding [attr.aria-expanded]="isOpen()" writes the attribute with the boolean value of the signal: with attr. Angular sets the HTML attribute, which is what assistive technologies read. The Angular documentation shows it with the same pattern ([attr.aria-valuenow]). An alternative that the code discards is putting role="button" on a div: it would force you to rewrite tabbing and keys, that is exactly what the native button gives for free.

A prudent criterion to decide whether you need ARIA: if an HTML element with the right semantics exists, use that and do not add roles that the element already has (a button does not need role="button"). ARIA is for the cases where HTML is not enough, and wrong ARIA makes the experience worse than no ARIA at all: the ARIA Authoring Practices guidelines say so too.

Focus in a single-page application

In a traditional page, navigation reloads the document and the screen reader starts again from the top. In an Angular application the router replaces the content without reloading anything: the focus stays where it was (often on the link just clicked, now gone) and whoever uses a screen reader does not know that the page has changed. A simple solution is a skip link at the start of the page and a main element with tabindex="-1" (focusable from code but outside the Tab order) to which the focus is moved after each completed navigation. The code of the previous version used document.getElementById directly, which with server-side rendering may not exist: here the DOCUMENT is injected.

focus-on-navigation.ts (compiled with ngc, not run)
import { DestroyRef, DOCUMENT, inject, provideAppInitializer } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';

/** Moves the focus to the <main> after every completed navigation. */
export const provideFocusOnNavigation = () =>
  provideAppInitializer(() => {
    const router = inject(Router);
    const doc = inject(DOCUMENT);
    const destroyRef = inject(DestroyRef);

    router.events
      .pipe(
        filter((e): e is NavigationEnd => e instanceof NavigationEnd),
        takeUntilDestroyed(destroyRef),
      )
      .subscribe(() => doc.getElementById('main-content')?.focus());
  });

You register it in the application configuration with provideFocusOnNavigation(). The takeUntilDestroyed closes the subscription when the injection context is destroyed, and the ?. operator avoids an error if the element is not there (for example on the error page). The trade-off: moving the focus on every navigation is right for page changes, but wrong for parameter changes that update the same view (a filter, pagination), where pulling the focus away from the user is worse than not moving it. If you have routes of this kind, restrict the filter to the events that change the path, not just the parameters.

Dialog windows

A modal window must do three things: move the focus inside itself, stop it from leaving with Tab and make the rest of the page inert. Angular's documentation mentions the CDK directive cdkTrapFocus for "modal dialogs where focus must be constrained". There is, however, an alternative that reduces the code: the native <dialog> element opened with showModal(), which according to MDN makes the rest of the page inert and where you can indicate with autofocus the element to land on.

confirm-delete.component.ts (compiled with ngc, not run in a browser)
import { Component, ElementRef, viewChild } from '@angular/core';

@Component({
  selector: 'app-confirm-delete',
  template: `
    <button type="button" (click)="open()">Delete</button>

    <dialog #dialog aria-labelledby="dialog-title" (close)="closed()">
      <h2 id="dialog-title">Confirm deletion</h2>
      <p>Do you want to delete this item?</p>
      <form method="dialog">
        <button value="cancel" autofocus>Cancel</button>
        <button value="delete">Delete</button>
      </form>
    </dialog>
  `,
})
export class ConfirmDeleteComponent {
  private readonly dialog = viewChild.required<ElementRef<HTMLDialogElement>>('dialog');

  protected open(): void {
    this.dialog().nativeElement.showModal();
  }

  protected closed(): void {
    const result = this.dialog().nativeElement.returnValue;
    console.log('result:', result);
  }
}

The form with method="dialog" closes the dialog and sets returnValue to the value of the button pressed, which is how the component reads the outcome. The "Cancel" button has autofocus because, in a destructive action, the safest starting point is the one that deletes nothing. MDN recommends using show() and showModal() instead of the open attribute. I did not run this component: the focus trap and the inertness are browser behaviours that I cannot show you with a test in Node.

Announcing what changes: LiveAnnouncer

When a search updates the results without moving the focus, whoever uses a screen reader does not know. The CDK's LiveAnnouncer writes a message into an aria-live region, which Angular's documentation indicates precisely for announcing messages to screen reader users. The previous version also put an aria-live region in the template, with the result that the same message is read twice: one is enough, and here the region is the one the service creates for you.

search.component.ts (compiled with ngc, not run)
import { Component, inject, signal } from '@angular/core';
import { LiveAnnouncer } from '@angular/cdk/a11y';

@Component({
  selector: 'app-search',
  template: `
    <label for="search">Search articles</label>
    <input id="search" type="search" (input)="search($event)" />
    <ul>
      @for (r of results(); track r) {
        <li>{{ r }}</li>
      }
    </ul>
  `,
})
export class SearchComponent {
  private readonly announcer = inject(LiveAnnouncer);
  protected readonly results = signal<string[]>([]);

  protected search(event: Event): void {
    const text = (event.target as HTMLInputElement).value;
    const found = this.filter(text);
    this.results.set(found);
    void this.announcer.announce(`${found.length} results for ${text}`, 'polite');
  }

  private filter(text: string): string[] {
    return ['Angular', 'Accessibility', 'Anatomy'].filter((s) => s.toLowerCase().includes(text.toLowerCase()));
  }
}

The template uses the new control flow (@for with track) instead of *ngFor, and the label is associated with the input via for/id: an aria-label would have been enough for the accessible name, but a visible label also helps those who see the page. The 'polite' priority waits for the screen reader to finish reading; 'assertive' interrupts, and should be reserved for errors that block the user. The number of results here depends on a fake list: in your application it comes from the real search.

Forms: labels, errors, descriptions

Forms concentrate the most common defects. A field without a label has no name for the screen reader; an error that appears only as red text is not communicated; a submit button disabled until the form is valid does not explain why it does not respond, and a disabled button is not even reachable with Tab. The following component leaves the button always enabled and, when an invalid form is submitted, marks the fields as touched so that the error appears.

contact.component.ts (compiled with ngc, not run in a browser)
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-contact',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()" novalidate>
      <label for="email">Email</label>
      <input
        id="email"
        type="email"
        formControlName="email"
        autocomplete="email"
        [attr.aria-invalid]="showError() ? 'true' : null"
        [attr.aria-describedby]="showError() ? 'email-error' : null"
      />
      @if (showError()) {
        <p id="email-error">Enter a valid email address, for example name&#64;example.com.</p>
      }
      <button type="submit">Send</button>
    </form>
  `,
})
export class ContactComponent {
  protected readonly form = inject(NonNullableFormBuilder).group({
    email: ['', [Validators.required, Validators.email]],
  });

  protected showError(): boolean {
    const c = this.form.controls.email;
    return c.invalid && (c.touched || c.dirty);
  }

  protected submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
  }
}

The two attributes work together. aria-invalid says that the value is not accepted and aria-describedby links the field to the paragraph that explains how to correct it, but both are written only when the error is present: in the previous version the field always pointed to an email-error identifier that sometimes did not exist, and a reference to a missing element is an error that axe reports. The message says what to do ("enter a valid address, for example..."), not just that something is wrong, as the criteria on error identification and description require.

role="alert" too is a choice: it announces the error immediately, but for a field validated while the user types it can become a nuisance. Here the message appears after the first contact with the field or after submission, and the screen reader reads it when the field takes focus because of aria-describedby. If instead you show an error summary at the top of the form, that deserves a role="alert".

Navigation menus: it is not a role="menu"

A widespread mistake is marking a site's navigation menu with role="menu" and role="menuitem". The W3C ARIA Authoring Practices say it explicitly in the disclosure navigation example: the word "menu" is used in a colloquial sense, but the implementation does not use the menu role, because that role promises assistive technologies a widget with complex keyboard handling (arrows, Home, End, search by initial) that a typical navigation does not offer. The previous version used role="menu" on a list of links and added a tabindex without ever really moving the focus: it promised a behaviour it did not deliver.

section-nav.component.ts: disclosure pattern (compiled with ngc, not run)
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-section-nav',
  template: `
    <nav aria-label="Main">
      <button type="button" [attr.aria-expanded]="isOpen()" aria-controls="guides-section" (click)="toggle()" (keydown.escape)="close()">
        Guides
      </button>
      @if (isOpen()) {
        <ul id="guides-section">
          <li><a href="/guides/angular">Angular</a></li>
          <li><a href="/guides/accessibility">Accessibility</a></li>
        </ul>
      }
    </nav>
  `,
})
export class SectionNavComponent {
  protected readonly isOpen = signal(false);
  protected toggle(): void { this.isOpen.update((v) => !v); }
  protected close(): void { this.isOpen.set(false); }
}

A button with aria-expanded opens a list of ordinary links, which remain reachable with Tab without handling the arrows. Escape just closes. It is less impressive than a menu with all the shortcuts, but it does what it declares. If you really need an application menu (a context menu, a toolbar menu) the work is much greater, and it is the case where it is better not to write it by hand.

When writing it by hand is not worth it: Angular Aria

Angular has a dedicated section and a package, @angular/aria, which the documentation describes as a collection of "headless and accessible" directives that implement the WAI-ARIA patterns and handle keyboard, ARIA attributes, focus and screen reader support: you provide HTML structure, styles and logic. On npm the package exists for Angular 21 (version 21.2.14 as of 2026-11-12). I did not install or try it in this guide, so I will not tell you how it is used: for complex widgets it is worth reading its page before rewriting keyboard and focus handling.

Contrast: compute it, do not guess it

Criterion 1.4.3 asks for 4.5:1 for normal text and 3:1 for large text; large text is defined by the W3C recommendation as at least 18 points or 14 points bold. In CSS pixels, with the conversion 1 point = 4/3 of a pixel, that is 24 px and about 18.67 px: the table of the previous version said "≥18px bold", a value that was too low. The ratio is computed from the relative luminance of the two colours, and the following program does it for a sample dark palette:

contrast.mjs (run with Node 24, identical output in two runs)
const channel = (c) => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
const luminance = (hex) => {
  const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
};
const contrast = (a, b) => {
  const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (high + 0.05) / (low + 0.05);
};

const background = '#0d1117';
const colors = { '--text-primary': '#e6edf3', '--text-secondary': '#8d96a0', '--text-link': '#58a6ff' };
for (const [name, value] of Object.entries(colors)) {
  console.log(`${name.padEnd(16)} ${value} on ${background}: ${contrast(value, background).toFixed(2)}:1`);
}

// Output (Node 24.11.0, identical in two runs):
// --text-primary   #e6edf3 on #0d1117: 16.02:1
// --text-secondary #8d96a0 on #0d1117: 6.31:1
// --text-link      #58a6ff on #0d1117: 7.49:1

The comments of the previous version declared 13.5:1, 4.7:1 and 5.2:1 for the same colours: none of the three matches the calculation, and the secondary text has far more contrast than the guide said. The practical point is that the numbers written in stylesheet comments are often copied or remembered: compute them with your real background, because contrast depends on the pair, not on the colour. The ratios obtained here concern text; for interface components (field borders, icons) criterion 1.4.11 asks for 3:1 and must be checked on their real state.

Verifying with tools, and seeing where they stop

axe-core is the rules engine used by many tools. In a unit test you can run it on a fragment of DOM. The listing tries it without a browser using jsdom, on two pages: one with the typical defects and the same one corrected. It runs only the level A and AA rules for WCAG 2.x (axe-core 4.14.0, jsdom 29.1.1).

axe_check.mjs: axe-core with jsdom (run, identical output in two runs)
import { JSDOM } from 'jsdom';
import axe from 'axe-core';

const BROKEN_PAGE = `<main>
  <h1>Contact</h1>
  <img src="map.png">
  <input type="email" name="email">
  <div class="btn" onclick="send()">Send</div>
</main>`;

const FIXED_PAGE = `<main>
  <h1>Contact</h1>
  <img src="map.png" alt="Map of the office">
  <label for="email">Email</label>
  <input id="email" type="email" name="email">
  <button type="button">Send</button>
</main>`;

const check = async (html) => {
  const dom = new JSDOM(`<!doctype html><html lang="en"><head><title>Test</title></head><body>${html}</body></html>`);
  const { window } = dom;
  const results = await axe.run(window.document.body, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] } });
  return results.violations.map((v) => `${v.id} (${v.nodes.length})`).sort();
};

console.log('broken page:', JSON.stringify(await check(BROKEN_PAGE)));
console.log('fixed page :', JSON.stringify(await check(FIXED_PAGE)));

// Output (Node 24.11.0, identical in two runs):
// broken page: ["image-alt (1)","label (1)"]
// fixed page : []

Two violations found, two fixed. But look at what is missing: the broken page also contained a <div onclick> used as a button, and axe did not report it. It is not a defect of the tool: a div with a click handler is not, for an automatic rule, an inaccessible control (it does not know it should be one). That is why accessibility does not end with an automatic test and why testing with the keyboard and with a screen reader remains indispensable. Another caveat: in jsdom the contrast checks do not work (there is no rendering engine), and axe indeed warned that the canvas getContext() method is not implemented: that family of rules must be run in a real browser.

In an Angular project the same check is written as a component test: you create the component, call fixture.detectChanges(), run axe.run(fixture.nativeElement) and verify that the violations are zero. I did not run that test (it requires your project's suite), and the "zero violations" result is obtained on an isolated component, not on a whole page. For a test in the browser with Playwright, on the blog you will find Playwright and axe-core for accessibility.

For the pipeline, Lighthouse has an accessibility category and the package for continuous integration is @lhci/cli, whose command is lhci (lhci autorun). I did not run them because they require Chrome, and I report no scores. Finally the screen reader: an automatic tool does not replace listening. NVDA and JAWS on Windows, VoiceOver on macOS and iOS, TalkBack on Android and Orca on Linux are the candidates; the practical rule is to try at least one complete path (filling in the form, opening the dialog, using the navigation) with only one of them, instead of knowing them all superficially.

What WCAG 2.2 adds

The nine new criteria, with the level that the W3C's "What's New in WCAG 2.2" page indicates for each, are these. For an Angular application some change the CSS, others the application flow.

  • 2.4.11 Focus Not Obscured (Minimum), AA: the element with the focus must not be completely covered, for example by a fixed header.
  • 2.4.12 Focus Not Obscured (Enhanced), AAA and 2.4.13 Focus Appearance, AAA: stricter versions on the visibility and the appearance of the focus.
  • 2.5.7 Dragging Movements, AA: every dragging function has a single-pointer alternative, for example "move up" and "move down" buttons in a sortable list.
  • 2.5.8 Target Size (Minimum), AA: pointer targets are at least 24 by 24 CSS pixels, except for exceptions such as sufficient spacing.
  • 3.2.6 Consistent Help, A: if help appears on several pages, it stays in the same relative position.
  • 3.3.7 Redundant Entry, A: in a multi-step process the user is not asked again for what they have already entered.
  • 3.3.8 Accessible Authentication (Minimum), AA and 3.3.9 (Enhanced), AAA: authentication must not require a cognitive test without an alternative; allowing paste into password fields and autofill is the first move.

A concrete consequence for Angular: the fixed header that many sites have can cover the field that receives the focus (2.4.11), a common technique to avoid it is scroll-padding-top or adjusting the scroll when the focus changes. And a password field with the right autocomplete and no paste blocking solves the most common part of 3.3.8. I do not give you code for these two cases because they depend on your layout.

A checklist you can actually use

Before handing over a component, these questions put back in order what the rest of the guide explains. They are not the text of WCAG: they are the filter I apply myself.

  • Can it be used with the keyboard alone, and is the Tab order the one you expect?
  • Is the focus always visible and not covered by other elements?
  • Does every control have an accessible name (label, text, aria-label where needed)?
  • Did I use a native element where one existed?
  • Are the states (open, selected, in error) exposed with attributes, not just with colour?
  • Are the contrasts computed on the real colour pair?
  • Is a dynamic change announced, without duplicates?

The seven questions are in order of cost: the first ones can be checked in a minute with the keyboard, the last ones require a tool or a screen reader. There is no need to answer all of them at once; the criterion is not to hand over the component without having answered the ones that cost nothing.

What you can do now

You can recognise the most widespread errors in Angular components (the double keyboard handler on the button, ARIA references to identifiers that do not exist, role="menu" on a navigation, doubled announcements), and you have the corrected versions, compiled with the compiler's strictest mode. You can compute a contrast, run axe-core on a fragment of DOM and read what it does not see. You know what WCAG 2.2 added. The next step is to try the keyboard on your most used component, then a screen reader on the path that takes your user to a result; and, if you want to understand the picture these rules start from, read what WCAG 2.1 AA means in practice and the implementation for public administration. If you are building a portfolio, contrast and the keyboard are also the criteria of how to create a developer portfolio.

Sources

The Angular components were compiled with ngc (@angular/compiler-cli 21.2.26, strictTemplates, extended diagnostics as errors, TypeScript 6.0.3, @angular/cdk 21.2.14), exit 0; they were not run in a browser. The programs contrast.mjs and axe_check.mjs were run with Node 24.11.0 (axe-core 4.14.0, jsdom 29.1.1), twice with identical output. All in a temporary folder outside the repository.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects