OiO.lk Blog CSS Context Menu positioning within scrollable element (angular)
CSS

Context Menu positioning within scrollable element (angular)


I’m using cdk-virtual-scroll-viewport to display a large list of elements like below

<cdk-virtual-scroll-viewport itemSize="115px" class="scrollable-card">
  <div *cdkVirtualFor="let project projects">
   <app-project-card [project]="project"></app-project-card>
  </div>
</cdk-virtual-scroll-viewport>

I have a contextmenu defined in app-project-card component like below

<mat-card class="project-card" (contextmenu)="onRightClick($event)">
  //other elements inside which are irrelavant
</mat-card>

<div style="visibility: hidden; position: fixed;" [style.left]="menuTopLeftPosition.x"
  [style.top]="menuTopLeftPosition.y" [matMenuTriggerFor]="menu"></div>

<mat-menu #menu="matMenu">
  <button mat-menu-item (click)="onEdit(project.id)"><mat-icon>edit</mat-icon>Edit</button>
  <button mat-menu-item (click)="onDelete(project.id)"><mat-icon>delete_outline</mat-icon>Delete</button>
</mat-menu>

Below is my code for onRightClick function.

onRightClick(event: MouseEvent) {
    event.preventDefault(); // Prevent the browser's default context menu
    // Set the position of the context menu
    this.menuTopLeftPosition.x = `${event.clientX}px`;
    this.menuTopLeftPosition.y = `${event.clientY}px`;
    // Open the context menu
    this.matMenuTrigger.openMenu();
  }

The problem I’m facing is that my context menu isn’t displayed on a correct coordinate. The coordinate seems to be calculated relative to the viewport, I’m not sure.

Scrolling the viewport changes the value of how much the y cordinate is off. x cordinate stays the same but seems to be off. Let me know if you need more context. Thank you



You need to sign in to view this answers

Exit mobile version