Skip to content

Context Menu Example

This example demonstrates how to implement a context menu that adapts its options based on the context—showing node-specific actions when a node is right-clicked, and diagram-wide actions otherwise.

import '@angular/compiler';
import { Component } from '@angular/core';
import { NgDiagramModelService, provideNgDiagram } from 'ng-diagram';
import { DiagramComponent } from './diagram.component';
import { ContextMenuService } from './menu/menu.service';
@Component({
imports: [DiagramComponent],
template: `<context-menu-example></context-menu-example> `,
styles: [
`
:host {
display: flex;
position: relative;
}
`,
],
providers: [ContextMenuService, NgDiagramModelService, provideNgDiagram()],
})
export class DiagramWrapperComponent {}
  • Context Awareness: Menu options change depending on whether a node or the diagram background is right-clicked.
  • Positioning: The menu appears at the exact cursor location using viewport coordinates.
  • Integration: Uses Angular signals and services for reactive state management.
  • Node Right-Click Handling:
    Nodes handle right-click events to show the context menu and select the node.

  • Diagram Right-Click Handling:
    Right-clicking the diagram background shows the diagram-wide menu.

  • Menu Positioning:
    The menu position is calculated using viewport coordinates.

  • Context Menu Service:
    The service manages the menu’s visibility, position, and context (node or diagram).

  • Menu Component:
    The menu component displays options based on the context and stores information about menu positioning.

  • Copy: Copies the selected node(s) to the clipboard.
  • Paste: Pastes copied nodes at the cursor position.
  • Delete: Removes the selected node(s).
  • Select All: Selects all nodes in the diagram.