Angular2 Catch the Delete button press from keyboard event

11,525

Solution 1

If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file. I can use the following function to perform delete keyboard press.

import { HostListener } from '@angular/core'; then use below function anywhere in your component ts file.

    @HostListener('document:keyup', ['$event'])
      handleDeleteKeyboardEvent(event: KeyboardEvent) {
        if(event.key === 'Delete')
        {
          // remove something... or call remove funtion this.remove();
        }
      }
remove(){ 
// code..
}

Solution 2

This way I used in my project to handle delete button use

@HostListener('document:keydown.delete', ['$event'])

I share for whom concern

@HostListener('document:keydown.delete', ['$event'])
onDeleteComponent(event: KeyboardEvent) {
    this.removeItem(this.selectedDashboardItem);
}

Solution 3

In angular2 using @HostListener to bind the keyboard events worked for me.

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

@Component({
  ...
})
export class AppComponent {

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

For more details, you can check the details here.

How can I listen for keypress event on the whole page?

Share:
11,525
Er. Bahuguna Goyal
Author by

Er. Bahuguna Goyal

Updated on June 27, 2022

Comments

  • Er. Bahuguna Goyal
    Er. Bahuguna Goyal almost 2 years

    I have multiple records in the gridview. I have option to select multiple records from the gridview.

    After selecting I want these selected records to be deleted.

    Anybody know how can I call the delete event to be called in angular2 when delete button is pressed from keyboard ?

  • Aviw
    Aviw over 4 years
    This works only for letters/number keys, but not for DEL