How To Disable Right Click Using AngularJS

In this blog, you will learn how to disable right click, using AngularJS.

In this blog, we will learn how to disable the right click button, using AngularJS. We will make a simple AngularJS Directive, which will not allow the user's mouse to right click and open the Context Menu.

To do this, we will override the default behaviour of the Context Menu. The contextmenu event is fired when the right button of the mouse is clicked (before the context menu is displayed) or when the context menu key is pressed (in this case, the context menu is displayed at the bottom left of the focused element, unless the element is a tree, where the context menu is displayed at the bottom left of the current row). We can also use this same event to customise our Context Menu.

  1. angular.module('app').directive('disableRightClick'function() {  
  2.     return {  
  3.         restrict: 'A',  
  4.         link: function(scope, element, attr) {  
  5.             element.bind('contextmenu'function(e) {  
  6.                 e.preventDefault();  
  7.             })  
  8.         }  
  9.     }  
  10. })  

To use this Directive in HTML code, you just need to add disable-right-click as the element's attribute. We simply use preventDefault(), which cancels the event, if it is cancelable, without stopping further propagation of the event. This prevents the Context Menu from being opened. There are many ways to go around this, but this should work fine for a normal internet user.