Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking on any item only shows the last index in the list instead of the specific index of the clicked item. For example, if my list contains 3 items, clicking on any item displays '2' as the index! I need guidance on how to ensure that the correct index of each list item is shown.
Below is the code snippet I am currently working with:
<div *ngFor="let item of items; let i = index" (contextmenu)="displayContextMenu($event); false">
<span> {{item}}</span>
<app-context-menu
*ngIf="rightClickMenuItems.length > 0 && isDisplayContextMenu"
[ngStyle]="getRightClickMenuStyle()"
[contextMenuItems]="rightClickMenuItems"
(onContextMenuItemClick)="handleMenuItemClick($event, i)"
></app-context-menu>
</div>
ts file:
items = ["item0","item1","item2"];
isDisplayContextMenu!: boolean;
rightClickMenuItems: Array<ContextMenu> = [];
rightClickMenuPositionX!: number;
rightClickMenuPositionY!: number;
displayContextMenu(event: any) {
this.isDisplayContextMenu = true;
this.rightClickMenuItems = [
{
menuText: 'Print index',
menuEvent: 'Handle print index',
},
];
this.rightClickMenuPositionX = event.clientX;
this.rightClickMenuPositionY = event.clientY;
}
handleMenuItemClick(event: any, index: number) {
switch (event.data) {
case this.rightClickMenuItems[0].menuEvent:
this.printIndex(index);
break;
}
}
printIndex(index: number){
alert(index);
}
@HostListener('document:click')
documentClick(): void {
this.isDisplayContextMenu = false;
}
getRightClickMenuStyle() {
return {
position: 'fixed',
left: `${this.rightClickMenuPositionX}px`,
top: `${this.rightClickMenuPositionY}px`
}
}
Context menu component:
.html:
<ng-container>
<div>
<div *ngFor="let menuItem of contextMenuItems; index as i"
(click)="onContextMenuClick($event, menuItem.menuEvent)">
{{ menuItem.menuText }}
</div>
</div>
</ng-container>
.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { ContextMenu } from '../../_models/contextMenu.model';
import { NgIf, NgFor } from '@angular/common';
@Component({
selector: 'app-context-menu',
templateUrl: './context-menu.component.html',
styleUrls: ['./context-menu.component.css'],
standalone: true,
imports: [NgIf, NgFor]
})
export class ContextMenuComponent {
@Input() contextMenuItems!: Array<ContextMenu>;
@Output() onContextMenuItemClick: EventEmitter<any> = new EventEmitter<any>();
onContextMenuClick(event: any, data: any): any {
this.onContextMenuItemClick.emit({
event,
data,
});
}
}
model:
export interface ContextMenu {
menuText: any;
menuEvent: any;
}