I want to handle a click event + CTRL keypress event in the same function in my component.ts file, but I don't seem to find a solution anywhere. I've tried:
@HostListener("click")
onDropdownItemClick( evt: keyboardEvent) {
console.log(evt.keyCode);
}
but it just returns "ERROR TypeError: Cannot read property 'keyCode' of undefined"
I've also tried this too:
@Component({
selector: '....',
templateUrl: '....',
host: {
'(window:keydown)': 'findKey($event)',
'(window:mousedown)': 'findKey($event)'
}
});
findKey(event) {
if(event.ctrlKey && event.which === 1){
console.log("CTRL + mouse-click");
}
}
But it's not working either. Anyone have suggestions on how to catch both events at the same time?
Turns out, you totally can. Run this demo in my JavaScript Demos project on GitHub. In Angular 1.
The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.
Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object. A component should define the onShow(event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc.
In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component.
The MouseEvent
event provides a ctrlKey
property that allows to read the state of the Ctrl key state when the click happened
@HostListener("click", ['$event'])
onDropdownItemClick( evt: MouseEvent) {
console.log('clicked - with ctrl pressed:', evt.ctrlKey);
}
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey
Just store the status of the control key in a field and read it in the click event:
ctrlDown = false;
@HostListener('window:keydown.ctrl')
onCtrlDown() {this.ctrlDown = true; }
@HostListener('window:keydown.ctrl')
onCtrlUp() {this.ctrlDown = false; }
@HostListener("click")
onDropdownItemClick( evt: keyboardEvent) {
console.log('clicked - with ctrl pressed:', this.ctrlDown);
}
If above doesn't work please try
@HostListener('window:keydown', ['$event'])
onCtrlDown(event) {this.ctrlDown = event.ctrlKey; }
@HostListener('window:keydown')
onCtrlUp() {this.ctrlDown = false; }
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