How to navigate/focus to the next item in Angular2?

后端 未结 1 1262
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 23:31

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 ano

相关标签:
1条回答
  • 2020-12-04 00:05

    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', []);
        }
      }
    }
    

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

    Update focusedIdx on key events:

           handleKeyEvent(event: Event): void {
                this.focusedIdx++;
            }
    

    See also Angular 2: Focus on newly added input element

    0 讨论(0)
提交回复
热议问题