Skip to content

Instantly share code, notes, and snippets.

@ElisePatrikainen
Last active January 21, 2021 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ElisePatrikainen/d4842dc74531500dada525498d65242b to your computer and use it in GitHub Desktop.
Save ElisePatrikainen/d4842dc74531500dada525498d65242b to your computer and use it in GitHub Desktop.
Simple form with focus and keyboard interaction
import { Component, ViewChild, ViewChildren, ElementRef, QueryList, HostListener, AfterViewInit } from '@angular/core';
import { FocusTrapFactory, FocusMonitor, ListKeyManager} from '@angular/cdk/a11y'
@Component({
selector: 'app-root',
template: `
<button (click)="testA11y()"> Test A11y! </button>
<div #element role="dialog" hidden=true>
<label>Sample field</label>
<input #elementChild>
<label>Sample field</label>
<input #elementChild>
<label>Sample field</label>
<input #elementChild>
<label>Sample field</label>
<input #elementChild>
<label>Sample field</label>
<input #elementChild>
</div>`
})
export class AppComponent implements AfterViewInit {
keyManager : any
@ViewChild('element') element : ElementRef;
@ViewChildren('elementChild') elementChild : QueryList<any>
constructor( private focusTrap: FocusTrapFactory,
private focusMonitor : FocusMonitor ) {}
ngAfterViewInit() {
this.keyManager = new ListKeyManager(this.elementChild)
this.keyManager.withHorizontalOrientation('ltr') // Arrow navigation options
this.keyManager.withWrap() // Arrow navigation options
}
/* Enables keyboard arrows navigation */
@HostListener('window:keyup', ['$event'])
keyFunc(event) {
if (event.code !== 'Tab') {
this.keyManager.onKeydown(event)
this.focusMonitor.focusVia(this.keyManager.activeItem.nativeElement, "keyboard")
}
else { // 'artificially' updates the active element in case the user uses Tab instead of arrows
this.keyManager.onKeydown(event)
this.keyManager.setNextItemActive()
}
}
/* Shows the form, puts focus on it and initialize keyboard navigation */
testA11y() {
this.element.nativeElement.hidden = false;
let focusTrap = this.focusTrap.create(this.element.nativeElement) // creates a focus trap region
focusTrap.focusInitialElement() // Moves the focus in the form (by default the first field)
this.keyManager.setFirstItemActive() // Sets the element we focused on as 'active' to the KeyManager
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment