使用箭头键进行Angular2导航 [英] Angular2 Navigation using Arrow Keys

查看:96
本文介绍了使用箭头键进行Angular2导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Angular2项目中工作,在该项目中我有一个项目列表,单击任何项​​目都会使用项目详细信息组件显示其详细信息页面.我正在尝试找到一种方法,允许用户使用左右箭头键浏览项目.

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.

我有两个组件ItemsListComponent和ItemDetailsComponent,每个组件都有自己的路线,ItemDetailsComponent有一个参数id.而且我有一个存储在ItemsService中的项目列表.

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.

我在ItemDetails组件中有两个按钮来显示Next和Previous项目,每个按钮都绑定到showNext(id)和showPrevious(id)函数.

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.

一切正常,但是我无法将向右/向左键KeyPress事件链接到showNext(id)和showPrevious(id)函数.

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

我想到了一种方法,该方法是在组件构造函数中的文档上使用addEventListener添加事件侦听器,但这似乎不是一个很好的解决方案.

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:我没有使用jQuery,因此正在寻找一个纯粹的Angular2解决方案

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

推荐答案

经过一番尝试,我找到了答案,这只需要在ItemDetailsComponent的主div上完成:

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

这篇关于使用箭头键进行Angular2导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆