Angular 4 - handle two events simultaneously

I want to handle the click click + CTRL keypress event in the same function in my component.ts file, but it seems I have not found a solution anywhere. I tried:

@HostListener("click")
    onDropdownItemClick( evt: keyboardEvent) {
        console.log(evt.keyCode);
    }

but it just returns "ERROR TypeError: cannot read property" keyCode "from undefined"

I also tried this:

@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 doesn’t work either. Anyone have suggestions on how to catch both events at the same time?

+4
source share
1 answer

The event MouseEventprovides a property ctrlKeythat allows you to read the state of a state Ctrlwhen a button is clicked.

@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

:

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);
}

,

@HostListener('window:keydown', ['$event'])
onCtrlDown(event) {this.ctrlDown = event.ctrlKey; }

@HostListener('window:keydown')
onCtrlUp() {this.ctrlDown = false; }

a >

+2

Source: https://habr.com/ru/post/1687275/


All Articles