在 Angular 2 中使用按键聚焦文本输入而不添加按键值

Focus text input with keypress in Angular 2 without adding keypress value

我在我的应用程序中添加了键盘快捷键,其中之一是 Shift + F,它会触发焦点方法具体输入,例如我的搜索字段。

输入元素可以存在于组件树中的任何位置,因此我的方法是使用带有 EventEmitter 的服务和监听它的指令。

一些组件

@Component({ .. })
export class SomeComponent {
  @HostListener('document:keypress', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    if (event.shiftKey) {
      let key = event.key;
      if (key === 'F') {
        this.focusService.focus('mySearchBox');
      }
    }
  }

  constructor(private focusService: FocusService) { }
}

我在 html 的某处应用了焦点指令。

<input focus="mySearchBox">

焦点指令

@Directive({
    selector: '[focus]'
})
export class FocusDirective implements AfterViewInit {
    @Input() focus: string;

    constructor(
        private elementRef: ElementRef,
        private focusService: FocusService) { }

    ngAfterViewInit() {
        this.focusService.focusSource.subscribe(res => {
            this.setFocus(res);
        });
    }

    setFocus(item: string) {
        // I use strings to match the call with the input
        if (this.focus === item) { // 'mySearchBox' === 'mySearchBox
            this.elementRef.nativeElement.focus();
            // Do something to avoid the keypress event
        }
    }
}

焦点服务

@Injectable()
export class FocusService {
  focusSource = new EventEmitter<string>();

  focus(string) {
    this.focusSource.emit(string);
  }
}

问题

如果我只是调用 focusService.focus('mySearchBox) 它会起作用,但是由于我正在监听键盘事件,焦点已设置并且 F 被添加 到输入值。

我能否以某种方式避免这种行为(最好在指令中),以便输入忽略按键?

我试过重置输入的值,但是 F 是在该方法完成后添加的,所以没有用。

尝试使用 preventDefault():

let key = event.key;
if (key === 'F') {
    event.preventDefault();
    this.focusService.focus('mySearchBox');
}

The event.preventDefault() method stops the default action of an element from happening.

详细了解 preventDefault() here

编辑:

您可能需要收听 keydown 事件而不是 keypress

@HostListener('keydown', ['$event'])