Last active
January 21, 2021 14:06
-
-
Save ElisePatrikainen/d4842dc74531500dada525498d65242b to your computer and use it in GitHub Desktop.
Simple form with focus and keyboard interaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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