Fiz as implementações, mas está retornando este erro no console.
core.js:4197 ERROR TypeError: Cannot read property 'focus' of undefined
at KeyboardManagerDirective.manageKeys (keyboard-manager.directive.ts:26)
at KeyboardManagerDirective_keyup_HostBindingHandler (keyboard-manager.directive.ts:8)
at executeListenerWithErrorHandling (core.js:14317)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:14352)
at HTMLDivElement.<anonymous> (platform-browser.js:582)
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27428)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:480)
O código está assim:
import { ElementRef } from '@angular/core';
import { Directive } from '@angular/core';
@Directive({
selector: '[appKeyboardManagedItem]'
})
export class KeyboardManagedItemDirective {
constructor(
private elementRef: ElementRef<HTMLElement>,
) { }
public focus(): void {
this.elementRef.nativeElement.focus();
}
public isFocused(): boolean {
return this.elementRef.nativeElement === document.activeElement;
}
}
@HostListener('keyup', ['$event'])
public manageKeys(event: KeyboardEvent): void {
switch (event.key) {
case 'ArrowUp':
this.moveFocus(ArrowDirection.RIGHT).focus();
break;
case 'ArrowDown':
this.moveFocus(ArrowDirection.LEFT).focus();
break;
case 'ArrowLeft':
this.moveFocus(ArrowDirection.LEFT).focus();
break;
case 'ArrowRight':
this.moveFocus(ArrowDirection.RIGHT).focus();
break;
}
}
public moveFocus(direction: ArrowDirection): KeyboardManagedItemDirective {
const items = this.items.toArray();
const currentSelectedIndex = items.findIndex(item => item.isFocused());
const targetElementFocus = items[currentSelectedIndex + direction];
if (targetElementFocus) {
return targetElementFocus;
}
return direction === ArrowDirection.LEFT ? items[items.length - 1] : items[0];
}
<div
appKeyboardManager
role="radiogroup"
[attr.aria-labelledby]="id"
class="button-group">
<label [attr.id]="id"> {{ label }}</label>
<button
appKeyboardManagedItem
role="radio"
[attr.aria-checked]="value === options.YES"
[attr.tabindex]="value === options.YES || value === null ? 0 : -1"
class="button button-yes"
type="button"
(click)="activate(options.YES)"
[class.button-pressed]="value === options.YES">
Yes
</button>
<button
appKeyboardManagedItem
role="radio"
[attr.aria-checked]="value === options.NO"
[attr.tabindex]="value === options.NO || value === null? 0 : -1"
class="button button-no"
type="button"
(click)="activate(options.NO)"
[class.button-pressed]="value === options.NO">
No
</button>
</div>
Alguma solução para isso?