如何导航/聚焦到Angular2中的下一个项目? [英] How to navigate/focus to the next item in Angular2?
问题描述
我想使用箭头键专注于下一个项目.
在keydown事件处理程序中,我使用event.currentTarget.nextSibling
访问下一项.
还有另一种方法可以实现这一目标吗?
在事件处理程序中,我想使用JQuery来做到这一点.这该怎么做?
I want to focus to the next item using Arrow keys.
In keydown event handler, I use event.currentTarget.nextSibling
to access the next item.
Is there another way to accomplish this?
In the event handler, I want to use JQuery to do this. How to do this?
<ul>
<li *ngFor = "let work of works" tabindex="-1"
(keydown.ArrowDown)="handleKeyEvent( $event, 'Arrow Down' )">
<div class="guide-label">
<div>{{work.cd}}</div>
<div>{{work.name}}</div>
</div>
</li>
</ul>
export class WorkComponent {
...
handleKeyEvent(event: Event): void {
event.currentTarget.nextSibling.focus();
event.preventDefault();
}
}
推荐答案
创建一个焦点指令(并将其注册到您的NgModule
中),当输入值更改为true
时,该指令在主机元素上调用focus()
:
Create a focus directive (and register it in your NgModule
) that calls focus()
on the host element when the input value changes to true
:
@Directive({
selector : '[myFocus]'
})
class MyFocus {
constructor(public renderer: Renderer, public elementRef: ElementRef) {}
@Input()
set myFocus(value :boolean) {
if(value) {
this.renderer.invokeElementMethod(
this.elementRef.nativeElement, 'focus', []);
}
}
}
添加选择器和一个绑定,该绑定在应被聚焦时将true
或false
传递给指令:
Add the selector and a binding that passes true
or false
to the directive when it is supposed to be focused:
<li *ngFor = "let work of works let idx=index" tabindex="-1"
[myFocus]="idx == focusedIdx" (keydown.ArrowDown)="handleKeyEvent( $event, 'Arrow Down' )">
在关键事件上更新focusedIdx
:
handleKeyEvent(event: Event): void {
this.focusedIdx++;
}
另请参见角度2:关注新添加的输入元素
这篇关于如何导航/聚焦到Angular2中的下一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!