Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Navigation using Arrow Keys

Tags:

angular

I am working on a Angular2 project in which I have a list of items and clicking any item display its details page using item details component. I am trying to find a way to allow users to navigate the items using right and left arrow keys.

So, I have a list of items and when for example user click the first item in the list it shows item details, what I want now is that when user press right arrow key it should automatically load the details of the next item in the list.

I have two components ItemsListComponent and ItemDetailsComponent each with its own route, ItemDetailsComponent has a parameter id. And I have list of items stored in a ItemsService.

I have two buttons in ItemDetails component to display Next and Previous item each bind to showNext(id), and showPrevious(id) functions on same component.

Everything works fine, but I am unable to link the Right/Left arrow KeyPress event to the showNext(id) and showPrevious(id) functions.

I thought of one approach which is add an event listener using addEventListener on document, in the component constructor but this doesnt seems to be an elegant solution.

Any help related to this would be highly appreciated.

PS: I am not using jQuery so looking for a pure Angular2 solution

like image 558
Naveed Ahmed Avatar asked Mar 20 '16 01:03

Naveed Ahmed


1 Answers

With some hit and trial, I found the answer, all it needed was this on my main div of the ItemDetailsComponent:

(window:keydown)="onKey($event)"
like image 54
Naveed Ahmed Avatar answered Sep 20 '22 12:09

Naveed Ahmed