I am trying to trace when a user presses a Shift+Tab combination key using keyboard, but I am not able to fire that event
@HostListener('keyup', ['$event'])
@HostListener('keydown', ['$event'])
onkeyup(event) {
if (event.keyCode == 16 && event.keyCode == 9) {
this.isShift = true;
console.log("On Keyup " + event.keyCode);
}
}
onkeydown(event) {
console.log("On KeyDown" + event.keyCode);
}
HostListener listens to host events, while HostBinding allows us to bind to a property of the host element. The host is an element on which we attach our component or directive. This feature allows us to manipulate the host styles or take some action whenever the user performs some action on the host element.
Introduction. @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.
HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.
Although the solution by Frank Modica works, using Angular's key event filtering and pseudo-events would be a more readable and cleaner solution:
@Directive({
selector: '[keyHandler]'
})
export class KeyHandlerDirective {
@HostListener('keydown.shift.tab', ['$event'])
onKeyDown(e) {
// optionally use preventDefault() if your combination
// triggers other events (moving focus in case of Shift+Tab)
// e.preventDefault();
console.log('shift and tab');
}
}
// in template:
<input type="text" keyHandler />
More examples of how pseudo-events work can be found here.
It works when I do this:
@Directive({
selector: '[test-directive]'
})
export class TestDirective {
@HostListener('keydown', ['$event']) onKeyDown(e) {
if (e.shiftKey && e.keyCode == 9) {
console.log('shift and tab');
}
}
}
<input type="text" test-directive />
Note that keyup
can be tricky because tab
may unfocus the element. So by the time keyup
fires, you may be on the next element, so keyup
may actually fire on that element. So it depends on what you need. But keydown
works for the current element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With