Angular › Accessibility (a11y) in Angular
How would you manage keyboard focus properly in an Angular modal dialog to keep it accessible?
AdvancedAnswer
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.