5

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 ?

TGrif
  • 5,725
  • 9
  • 31
  • 52
Er. Bahuguna Goyal
  • 192
  • 1
  • 3
  • 10
  • The docs show how to handle the Enter key. You can follow the same process for the delete key: https://angular.io/guide/user-input#key-event-filtering-with-keyenter – DeborahK Aug 21 '17 at 20:58
  • just simply check the `Delete` key code and perform actions accordingly – Pardeep Jain Aug 22 '17 at 17:07

3 Answers3

8

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..
}
Prabhat Maurya
  • 1,058
  • 16
  • 21
4

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);
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
1

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?

Er. Bahuguna Goyal
  • 192
  • 1
  • 3
  • 10