Performance: Keyboard navigation support
Keyboard navigation affects user interaction responsiveness and visual stability during keyboard-driven page use.
Jump into concepts and practice - no test required
import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core'; import { FocusKeyManager } from '@angular/cdk/a11y'; @Component({ standalone: true, template: ` <div (keydown)="onKeydown($event)" tabindex="0"> <button #btn1>Button 1</button> <button #btn2>Button 2</button> </div> ` }) export class MyComponent implements AfterViewInit { private keyManager!: FocusKeyManager<ElementRef>; @ViewChildren('btn1, btn2') buttons!: QueryList<ElementRef>; ngAfterViewInit() { this.keyManager = new FocusKeyManager(this.buttons).withWrap(); } onKeydown(event: KeyboardEvent) { this.keyManager.onKeydown(event); } }
<!-- Angular template --> <button (keydown)="onKeyDown($event)">Click me</button> // Component onKeyDown(event: KeyboardEvent) { if (event.key === 'ArrowDown') { // Manually manipulate DOM focus with document.querySelector const next = document.querySelector('#nextElement'); if (next) next.focus(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct DOM focus manipulation on keydown | Multiple direct DOM queries and focus calls | Multiple reflows per key event | High paint cost due to layout shifts | [X] Bad |
| Angular CDK FocusKeyManager usage | Managed focus updates via Angular bindings | Single reflow per key event | Low paint cost with stable layout | [OK] Good |
<button #btn1 (keydown.arrowdown)="focusNext(1)">One</button> <button #btn2 (keydown.arrowdown)="focusNext(2)">Two</button> <button #btn3>Three</button>
Assuming focusNext(index) sets focus to the button at that index, which button gets focused after pressing 'ArrowDown' on button 1?
@ViewChildren('btn') buttons: QueryList<ElementRef>;
focusNext(index: number) {
this.buttons.toArray()[index].nativeElement.focus;
}What is the error preventing focus from moving?