Back to results for “Angular CDK (Component Dev Kit)”
Angular › Accessibility (a11y) in Angular

How would you manage keyboard focus properly in an Angular modal dialog to keep it accessible?

Advanced

Answer

When a modal opens, focus should move into the modal automatically, and it should stay trapped inside the modal while it is open so a keyboard user cannot accidentally tab to content behind it. The Angular CDK's FocusTrap directive handles this trapping automatically, and you can move focus back to the triggering element when the modal closes.
import { FocusTrapFactory } from '@angular/cdk/a11y';

@Component({
  selector: 'app-modal',
  template: `<div cdkTrapFocus><ng-content></ng-content></div>`
})
export class ModalComponent {}
Real-world example A checkout page traps keyboard focus inside its payment confirmation modal using the cdkTrapFocus directive, so a user pressing Tab repeatedly stays inside the dialog instead of jumping back to the page behind it.

Common follow-ups: What happens to focus when the modal closes, and how do you restore it correctly?;What ARIA role and attributes are expected on a modal dialog?