What approach would you recommend to control the whole app with keyboard only? I found Spotlight lib, but it depends on enyojs which seems to have its own component model and overall enyojs seems to be an overkill.
So far I'm listening on keydown events in app.component.ts
:
@HostListener('window:keydown', ['$event']) onKeydown(event: any) {
event.preventDefault();
this.mainKeydownHandler.handle(event.keyCode);
}
Each component which want to handle keydown events registers to MainKeydownHandler
's handlers and when keydown event occures MainKeydownHandler
delegates an event to the registered handler. The appropriate handler is determined by document.activeElement
's class (I did not find more "angular2-like" way to get currently focused elem) in MainKeydownHandler
's handle method. So now I have to add appropriate class name to a group of elements I want to be able to focus.
Furthermore, component's handler gets all selectable elements with:
@ViewChildren('selectable') elements: QueryList<ElementRef>;
so I need to add #selectable
and class with ID of handler to each element I want to focus. Component's handler then receives keyCode
and determines which element to select next, or return to previouslly selected elem from another component and so on.
This approach seems awkward, involves quite a lot of code when new component want to handle keydown events and there are situations when a component completely loses focus: when I delete an item from some list and then this component is rerendered (some service or MainKeydownHandler
could remember, but this could lead to quite a lot of elements to remember along the way navigating user through components).
Is there a better, simpler, more generic and more declarative way to control entire angular2 app with keyboard-only (keydown/keyup events)?
Alternatively, is it reasonable to use Spotlight (with enyojs dep.) with angular2 for this use-case? And can you provide working plunker with angular2+spotlight. I could not get these two to work together.