Javascript 在角度2中使用按键对文本输入进行对焦,而不添加按键值
我正在我的应用程序中添加键盘快捷键,其中一个是Shift+F,它会在特定输入(例如我的搜索字段)上触发聚焦方法 输入元素可以存在于组件树中的任何位置,因此我的方法是使用带有EventEmitter的服务和侦听它的指令 SomeComponentJavascript 在角度2中使用按键对文本输入进行对焦,而不添加按键值,javascript,angular,focus,keypress,Javascript,Angular,Focus,Keypress,我正在我的应用程序中添加键盘快捷键,其中一个是Shift+F,它会在特定输入(例如我的搜索字段)上触发聚焦方法 输入元素可以存在于组件树中的任何位置,因此我的方法是使用带有EventEmitter的服务和侦听它的指令 SomeComponent @Component({ .. }) export class SomeComponent { @HostListener('document:keypress', ['$event']) onKeyDown(event: KeyboardEve
@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的某个地方,我应用了一个focus指令
<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);
}
}
@Injectable()
导出类聚焦服务{
focusSource=新的EventEmitter();
焦点(字符串){
this.focusSource.emit(字符串);
}
}
问题
如果我只调用focusService.focus('mySearchBox'),它可以工作,但是因为我正在监听键盘事件,设置了焦点,并将F添加到输入值中
我能否以某种方式避免这种行为(最好是在指令中),以便输入忽略按键
我已尝试重置输入值,但F在方法完成后被添加,因此没有任何用处。尝试使用
preventDefault()
:
preventDefault()方法停止元素的默认操作
阅读有关preventDefault()
的更多信息
编辑:
您可能需要收听keydown
事件,而不是keypress
@HostListener('keydown', ['$event'])
@HostListener('keydown', ['$event'])