If you want display your own customized context menu on right mouse click, this program will help you.
Source Code            DEMO

Disable Context Menu

Whenever user right click on HTML document, The browser will show one default menu. We have to disable this first to display your own menu. You can do this by using below code.
<body oncontextmenu="return false">

Design  Your Own Context Menu

Design a DIV with absolute position and limited width. Find the following basic design.
.rightClickPanel {
  border:1px solid #ccc;


Whenever user clicks on the div, detectRightMouseClick will  be called. This function will detect right mouse click, and displays context menu exactly at that location. clickOutside is the directive which detects outside click of the context menu, so we can close it.
<div (mouseup)="detectRightMouseClick($event)" style="border:1px solid #ccc;padding:15px;width:100%">
    Right Mouse click here
<div class="rightClickPanel" [ngStyle]="rightPanelStyle" (clickOutside)="closeContextMenu()">
    My right panel

Set Style to Context Menu based on Mouse Position

  1. $event.which - Key code of event ( 3 for right mouse click )
  2. $event.clientX - X coordinate of mouse click
  3. $event.clientY - Y coordinate of mouse click


Observe detectRightMouseClick fucntion
import { Component } from '@angular/core';
  selector: 'my-app',
  template: `
    <div (mouseup)="detectRightMouseClick($event)" style="border:1px solid #ccc;padding:15px;width:100%">
    Right Mouse click here
    <div class="rightClickPanel" [ngStyle]="rightPanelStyle" (clickOutside)="closeContextMenu()">
    My right panel
export class AppComponent {
  rightPanelStyle: Object = {};
  detectRightMouseClick($event) {
       if($event.which === 3) {
            this.rightPanelStyle = {'display':'block','left':$event.clientX + 'px','top':$event.clientY + 'px'};
            return false;

  closeContextMenu() {
      this.rightPanelStyle = {'display':'none'};

clickOutSide directive

This directive is for detecting click outside of the context menu
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';

    selector: '[clickOutside]'
export class ClickOutsideDirective {
    constructor(private _elementRef: ElementRef) {

    public clickOutside = new EventEmitter<MouseEvent>();

    @HostListener('document:click', ['$event', '$event.target'])
    public onClick(event: MouseEvent, targetElement: HTMLElement): void {
        if (!targetElement) {

        const clickedInside = this._elementRef.nativeElement.contains(targetElement);
        if (!clickedInside) {


  1. When i right click i am getting default browser's options, how can we disable them ?



Follow this blog by Email

Popular Posts