Skip to main content

Create Custom Context Menu in Angular

 As professional Angular developers sometimes we come across unconventional requirements. One such requirement is to override the browser’s right-click context menu and provide a custom context menu.

There are a few ways to approach this requirement. One way is to use Angular CDK. A great article on this can be found here.

Another way is to leverage the contextmenu event of HTML elements. This event is supported by all major browsers as can be seen below from MDN documentation. This is the approach we will take in this article.

A screen grab from https://developer.mozilla.org/ showing the browser compatibility matrix for contextmenu event.

This approaches’ simplicity comes from the fact that we just need the understanding of Angular’s parent-child communication to achieve our objective.

So, let’s get started.

Our app component template is as below.

<div class="container">
  <div class="element" (contextmenu)="displayContextMenu($event); false">
    <span>Right click on me!</span>
    <app-context-menu
      *ngIf="rightClickMenuItems.length > 0 && isDisplayContextMenu"
      [ngStyle]="getRightClickMenuStyle()"
      [contextMenuItems]="rightClickMenuItems"
      (onContextMenuItemClick)="handleMenuItemClick($event)"
    ></app-context-menu>
  </div>
</div>

The contextmenu event is handled on the div with class element. Notice the false after the event handler method call. This is important as it prevents the default right click browser context menu from opening.

The AppContextMenu component is embedded as a child component with conditional rendering using *ngIf. Eventually, this component will be rendered when the user right-clicks on the div with class element.

Image for post

Let’s have a look at the AppComponent class.

import { Component, HostListener } from '@angular/core';
import { ContextMenuModel } from './Interfaces/context-menu-model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'context-menu';

  isDisplayContextMenu: boolean;
  rightClickMenuItems: Array<ContextMenuModel> = [];
  rightClickMenuPositionX: number;
  rightClickMenuPositionY: number;

  displayContextMenu(event) {

    this.isDisplayContextMenu = true;

    this.rightClickMenuItems = [
      {
        menuText: 'Refactor',
        menuEvent: 'Handle refactor',
      },
      {
        menuText: 'Format',
        menuEvent: 'Handle format',
      },
    ];

    this.rightClickMenuPositionX = event.clientX;
    this.rightClickMenuPositionY = event.clientY;

  }

  getRightClickMenuStyle() {
    return {
      position: 'fixed',
      left: `${this.rightClickMenuPositionX}px`,
      top: `${this.rightClickMenuPositionY}px`
    }
  }

  handleMenuItemClick(event) {
    switch (event.data) {
      case this.rightClickMenuItems[0].menuEvent:
           console.log('To handle refactor');
           break;
      case this.rightClickMenuItems[1].menuEvent:
          console.log('To handle formatting');
    }
  }

  @HostListener('document:click')
  documentClick(): void {
    this.isDisplayContextMenu = false;
  }

}

Notice the way in which the rightClickMenuItems property is set. It’s an array of type ContextMenuModel which allows us to configure different menu texts and corresponding events. Later these events are emitted back to the parent component when the user clicks an item on the context menu.

To display the context menu at right click position we have extracted the clientX and clientY properties of the contextmenu event object. These are later leveraged in getRightClickMenuStyle method and hooked up to AppContextMenu component using ngStyle.

Now, let’s have a look at the context-menu component template.

<ng-container>
  <div
    class="menu-link"
    *ngFor="let menuItem of contextMenuItems; index as i"
    (click)="onContextMenuClick($event, menuItem.menuEvent)">
    {{ menuItem.menuText }}
    <hr *ngIf="i < contextMenuItems.length - 1" />
  </div>
</ng-container>

It loops over the input property contextMenuItemsto generate a list of menu links using *ngFor. Note how the click event handler is passing the event menuItem.menuEvent that needs to be raised based on the input data received from the parent.

The ContextMenuComponent class consists of just an input and an output properties.

import { Component, Input, Output, EventEmitter } from "@angular/core";
import { ContextMenuModel } from "../Interfaces/context-menu-model";

@Component({
  selector: "app-context-menu",
  templateUrl: "./context-menu.component.html",
  styleUrls: ["./context-menu.component.css"],
})
export class ContextMenuComponent {
  @Input()
  contextMenuItems: Array<ContextMenuModel>;

  @Output()
  onContextMenuItemClick: EventEmitter<any> = new EventEmitter<any>();

  onContextMenuClick(event, data): any {
    this.onContextMenuItemClick.emit({
      event,
      data,
    });
  }
}

In a sense, it is a perfect dumb component and hence best for reusability! The parent component has complete control over the way it wants to use the context menu.

Based on the user’s selection on the custom context menu, the handler method emits output events with appropriate data. Now it’s up to the parent to handle the events the way it is supposed to based on the use case. For simplicity, we are just console logging here.

handleMenuItemClick method in app.component.ts

Before we wrap up, let’s discuss how we can close the context menu.

It’s fairly simple. A document click event listener has been set up on the AppComponentthat sets the isDisplayContextMenu flag to false.

host listener for handling document click events

And that’s it! We now have an extremely simple yet reusable custom context menu using only the basics of Angular.





















































































































Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...