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

时间:2017-01-11 14:41:14

标签: javascript angular focus keypress

我正在我的应用程序中添加键盘快捷键,其中一个是 Shift + F ,它触发特定输入的聚焦方法,例如我的搜索字段。

input-element可以存在于组件树的任何地方,所以我的方法是使用带有EventEmitter的Service和一个监听它的Directive。

SomeComponent

@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">

FocusDirective

@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,所以没有用。

1 个答案:

答案 0 :(得分:2)

尝试使用preventDefault()

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

event.preventDefault()方法停止发生元素的默认操作。

详细了解preventDefault() here

编辑:

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

@HostListener('keydown', ['$event'])
相关问题