Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created May 17, 2018 14:01
Show Gist options
  • Save amcdnl/029c9b8d6ca867b7ef92f7f7e37e1ec4 to your computer and use it in GitHub Desktop.
Save amcdnl/029c9b8d6ca867b7ef92f7f7e37e1ec4 to your computer and use it in GitHub Desktop.
import { Directive, HostBinding, HostListener, ElementRef } from '@angular/core';
import { KeyboardNavigationDirective } from './keyboard-navigation.directive';
@Directive({
selector: '[keyboardNavigationItem]'
})
export class KeyboardNavigationItemDirective {
@HostBinding('attr.tabindex') tabIndex = -1;
@HostBinding('class.keyboard-navigation-item') can = true;
constructor(
private _elementRef: ElementRef,
private _keyboardNavigation: KeyboardNavigationDirective
) {}
/**
* On click, focus the item.
*/
@HostListener('click')
onClick() {
this._elementRef.nativeElement.focus();
}
/**
* On keydown, direct to the previous or next element in the keyboard manager.
*/
@HostListener('keydown', ['$event'])
onKeydown(event: KeyboardEvent) {
if (event.key === 'ArrowUp') {
this._keyboardNavigation.previous(this._elementRef.nativeElement);
} else if (event.key === 'ArrowDown') {
this._keyboardNavigation.next(this._elementRef.nativeElement);
}
}
}
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[keyboardNavigation]'
})
export class KeyboardNavigationDirective {
@Input('keyboardNavigationType') type: 'focus' | 'click' = 'click';
constructor(private _elementRef: ElementRef) {}
/**
* Focus the previous element in the index.
*/
previous(element) {
const items = this.getItems();
const idx = items.findIndex(i => i === element);
if ((idx - 1) >= 0) {
items[idx - 1][this.type]();
}
}
/**
* Focus the next element in the index.
*/
next(element) {
const items = this.getItems();
const idx = items.findIndex(i => i === element);
if ((idx + 1) < items.length) {
items[idx + 1][this.type]();
}
}
/**
* Get the list of items in view.
*/
getItems(): any[] {
return Array.from(this._elementRef.nativeElement.getElementsByClassName('keyboard-navigation-item'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment