Dynamic context menu on PrimeNG p-tree component
Posted: 19 Jan 2021, 14:52
I'm using PrimeNG UI library v10 in an Angular application. I have a `p-tree` component that show a list of items that must show a context menu when the user right-clicks on them. The problem is that each item will have different options, depending on its type. So, I'd need to run some logic to show/hide the appropriate context menu options before they're popped. This is the code:
I've tried binding the `contextMenu` property to a method that returns the `ContextMenu` reference and run the logic there, but it didn't work. Something like:
The above code shows the context menu, but I can't click on any option (it does nothing). Another approach would be to add a `contextmenu` event listener to each of the tree items to show a custom context menu for each of them, but I don't like it, as there could be potentially hundreds of items, with its corresponding listeners. Any suggestion on a more optimal approach?
Thanks in advance,
Code: Select all
<p-tree [value]="treeItems" selectionMode="single" [(selection)]="selectedItem" [contextMenu]="treeContextMenu"></p-tree>
<p-contextMenu #treeContextMenu [model]="menuItems"></p-contextMenu>
I've tried binding the `contextMenu` property to a method that returns the `ContextMenu` reference and run the logic there, but it didn't work. Something like:
Code: Select all
<p-tree [value]="treeItems" selectionMode="single" [(selection)]="selectedItem" [contextMenu]="buildContextMenu()"></p-tree>
<p-contextMenu #treeContextMenu [model]="menuItems"></p-contextMenu>
// IN THE COMPONENT CODE:
@ViewChild('treeContextMenu') treeContextMenu: ContextMenu;
public buildContextMenu(): ContextMenu {
// NOTE: getItemMenuOptions is a method that return the appropriate items to show for the selected item in the tree
const menuItemsToShow = this.getItemMenuOptions();
// Update the context menu items (so it'll be updated in the 'treeContextMenu' component)
this.menuItems = menuItemsToShow;
// Return the reference to the context menu
return this.treeContextMenu;
}
Thanks in advance,