Reputation: 39160
I want to use tab key to perform some logic but not actually change the focus. According to this answer's comments I can use false in my markup or preventDefault() in the method. I have both like this.
onKey(event: KeyboardEvent) {
event.preventDefault();
if(event.key = "Tab") { this.update.emit(this.config); }
}
<input #input
title="{{config|json}}"
value="{{config.value}}"
(keyup)="onKey($event)"
(keydown.Tab)="onKey($event);false;">
Still, it gets an extra jump when I hit tab key. When I tried the very same logic but based on other keys (e.g. "a" or "enter"), the behavior is as expected, so I conclude that the logic is correct. For some reason, by tab is unruly and propagates the event as if I want to tab twice.
Am I handling tab key up incorrectly? Not sure what to google for other than what I already have.
Upvotes: 7
Views: 9538
Reputation: 15214
Try to use this code:
import { HostListener } from '@angular/core';
@HostListener('document:keydown.tab', ['$event'])
onKeydownHandler(event: KeyboardEvent) {
event.preventDefault();
}
Upvotes: 3
Reputation: 1794
Extract from the stackblitz : https://stackblitz.com/edit/angular-gbuwma?embed=1&file=src/app/app.component.ts
ts
import { Component, ViewChild, ElementRef,ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private changeDetector: ChangeDetectorRef) { }
@ViewChild("input2") input2: ElementRef;
onKey(event: KeyboardEvent) {
event.preventDefault();
if (event.key === "Tab") {
console.log('ole... tab');
this.input2.nativeElement.value = "aha";
this.changeDetector.detectChanges();
this.input2.nativeElement.focus();
}
}
}
html
<input #input
title=""
value=""
(keydown.Tab)="onKey($event);false;">
- - -
<input #input2
title=""
value=""
(keydown.Tab)="onKey($event);false;">
Upvotes: 3