52

In Angular is there a way to catch right click events? I see (click) and (dblclick), but when I try (rightclick) it does not trigger any events. Is there a way to include right click events and have them be handled by a function similar to the click and dblclick if it does not exist?

Narm
  • 10,677
  • 5
  • 41
  • 54
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 2
    see this link https://stackblitz.com/edit/angular-bjy6zb?embed=1&file=app/app.component.ts&hideExplorer=1&hideNavigation=1 – SEY_91 Apr 02 '18 at 23:10
  • Possible duplicate of [Angular 2 right click events?](https://stackoverflow.com/questions/41670017/angular-2-right-click-events) – Narm Apr 03 '18 at 02:22

3 Answers3

89

The event name is contextmenu. So, your html template code can be something like this:

<div (contextmenu)="onRightClick($event)"></div>

$event is an optional parameter so your template and event handler can look like this:

<div (contextmenu)="onRightClick()"></div>

onRightClick() {
    return false;
}

NOTE: You can return false; to avoid default browser action from the event.

Zzz
  • 2,927
  • 5
  • 36
  • 58
13

The event name is "contextmenu", so you should use something like this:

<button (contextmenu)="onRightClick($event)"> Right click me </button>

Then the onRightClick function should look something like this:

onRightClick(event) {
 event.preventDefault() //this will disable default action of the context menu
 //there will be your code for the expected right click action
}
vnapastiuk
  • 609
  • 7
  • 12
4

Do it Angular way with the help of decorator @HostListener

@HostListener('contextmenu')
preventContextMenu() {
    return false;
}

This code prevents native browser context menu to be opened within boundaries of component. Thus you can also open your customly created overlay menu within the same method before returning.

Looks clean, doesn't clutter the template.

Maxime Lyakhov
  • 140
  • 1
  • 11