Angular2 Navigation using Arrow Keys

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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

回答1:

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)"



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!