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++;
}