ngx-contextmenu
ngx-contextmenu copied to clipboard
iterate contextMenuItem over a property from contextMenuSubject
Is there one way to iterate with contextMenuItem over a property from contextMenuSubject?
Something like this:
<context-menu #testMenu> <ng-template let-item *ngFor="let x of item.elements" contextMenuItem> {{x.Name}} </ng-template> </context-menu>
<span [contextMenu]="testMenu" [contextMenuSubject]="testObject"></span>
with
let testObject = { elements: [ {Name: "Hello!"}, {Name: "Hello World!"}, ] }
There are a couple ways you could do this:
I'm assuming you have more than one testObject that you need to build a custom context menu for.
- Build a separate
<context-menu>for eachtestObject
<ng-container *ngFor="let testObject of testObjects">
<span [contextMenu]="testMenu" [contextMenuSubject]="testObject"></span>
<!-- This testMenu is scoped within the *ngFor testObject context, so that each [contextMenu] refers to its own instance -->
<context-menu #testMenu> <ng-template let-item *ngFor="let x of testObject.elements" contextMenuItem> {{x.Name}} </ng-template> </context-menu>
</ng-container>
- Track the "selected" item and dynamically change the
contextMenuItems on a single<context-menu>
<ng-container *ngFor="let testObject of testObjects">
<span [contextMenu]="testMenu" [contextMenuSubject]="testObject" (contextmenu)="selectedTestObject = testObject"></span>
</ng-container>
<context-menu #testMenu> <ng-template let-item *ngFor="let x of selectedTestObject.elements" contextMenuItem> {{x.Name}} </ng-template> </context-menu>
Let me know if that helps.
Thank you for your help, but with both variants I've problems:
-
The testObjects-elements are display in a svg-Tag. In The SVG-Tag I can't use
<ng-container *ngFor="let testObject of testObjects"> -
I works, but only by the second click on the element. By the first click the context-menu show the content from the last element. I think the contextMenu is open before (contextmenu)="selectedTestObject = testObject" change the content of the menu
So try modified option 2:
<ng-container *ngFor="let testObject of testObjects">
<span (contextmenu)="onContextMenu(testObject, $event)"></span>
</ng-container>
<context-menu #testMenu> <ng-template let-item *ngFor="let x of selectedTestObject.elements" contextMenuItem> {{x.Name}} </ng-template> </context-menu>
onContextMenu(selected: any, event: MouseEvent) {
this.selectedTestObject = selected;
$event.preventDefault();
setTimeout(() => {
this.contextMenuService.show.next({
event: $event,
item: this.selectedTestObject,
});
});
}
Thanks Isaac for your continued support on this library. I had the same problem (dynamic context menu on SVG objects) and modified option 2 works very well for this.