Hashmat
Hashmat

Reputation: 767

How can I detect when a key is pressed or released in Angular 'without input'?

I have a boolean variable which is by default false. So now, I want the variable to become 'true' when a key is pressed and 'false' the key is released.

Example: When I press the shift key, the declared variable should return true and when I released it, the variable should return false.

I know Angular JS has two keyboard events (keydown and Keyup) but as long as I know, in most cases, they're only used with 'input' fields. So is there an alternative to utilize the methods without an input field?

Upvotes: 0

Views: 5995

Answers (2)

Samet Karaca
Samet Karaca

Reputation: 103

@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
   console.log(event);
}
@HostListener('window:keydown', ['$event'])
keyEvent(event: KeyboardEvent) {
   console.log(event);
}

Upvotes: 4

Sawant Sharma
Sawant Sharma

Reputation: 758

I would use @HostListener decorator within your component:

import { HostListener } from '@angular/core';

@Component({
  ...
})

export class AppComponent {

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}

Put your conditions inside that block & you'll be gtg. There exists other ways too just so you know.

Upvotes: 2

Related Questions