28

I am building an interactive web application with Angular2 and I am looking for a way to capture right clicks on an angular component. I also need to prevent the browser context menu appearing on a right click so I can display my own custom context menu.

I know that in angular 1, you had to create a custom directive to capture a right click event. Is this still the case in Angular 2, or is it built in/is there an easier way of doing it? I've had a look through some previous SO questions but they do not relate to Angular2.

How can I accomplish capturing right clicks and preventing the browser context menu from appearing in Angular2?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
JavascriptLoser
  • 1,853
  • 5
  • 34
  • 61

1 Answers1

60

In Angular 2+, you can capture any event like:

<div (anyEventName)="whateverEventHandler($event)">
</div>

Note that $event is optional, and the return of the function is the return of the event handler, so, you can return false; to avoid default browser action from the event.

In your case the event name is contextmenu. So, your code can be something like this:

@Component({
  selector: 'my-app',
  template: `
    <div (contextmenu)="onRightClick($event)">
      Right clicked
      {{nRightClicks}}
      time(s).
    </div>
  `,
  // Just to make things obvious in browser
  styles: [`
    div {
      background: green;
      color: white;
      white-space: pre;
      height: 200px;
      width: 200px;
    }
  `]
})
export class App {
  nRightClicks = 0;

  constructor() {
  }

  onRightClick() {
    this.nRightClicks++;
    return false;
  }
}

Here's a full working example:
http://on.gurustop.net/2E0SD8e

Meligy
  • 35,654
  • 11
  • 85
  • 109
  • 1
    How can we do same for full page? I want to disable right click for whole page – bpbhat77 Feb 21 '17 at 06:52
  • 10
    Yes, you can use `@HostListener('document:contextmenu', ['$event'])`, here's an updated example: https://embed.plnkr.co/YasKxNbBDwbFXw96LCr1/?show=src%2Fapp.ts,preview If you need to do it dynamically, follow http://stackoverflow.com/questions/35080387/dynamically-add-event-listener-in-angular-2/35082441#35082441 – Meligy Feb 22 '17 at 00:48
  • @Meligy please add this as a separate answer, some people may miss it and it's obviously the correct answer. – AsGoodAsItGets May 21 '21 at 11:45