ngx-contextmenu
ngx-contextmenu copied to clipboard
Create dinamic context menu, without html template
Is it possible to create dynamic context menu, without html template?
It is explained in the documentation how to create dynamic context menu, but have to use html template.
In my case, I want to implement it as a directive:
Html:
<div myDirective>div on which I want to display my dynamic context menu</div>
Directive:
import { Directive, OnInit, ElementRef, Renderer } from '@angular/core';
import { ContextMenuService, ContextMenuComponent } from 'ngx-contextmenu';
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements OnInit {
constructor(private elementRef: ElementRef,
private renderer: Renderer,
private contextMenuService: ContextMenuService) {
}
ngOnInit() {
this.renderer.listen(this.elementRef.nativeElement, 'contextmenu', (event: MouseEvent) => {
let menu = new ContextMenuComponent(this.contextMenuService, null, el, null);
this.contextMenuService.show.next({
anchorElement: event.target,
contextMenu: menu,
item: null,
event: event
});
event.preventDefault();
event.stopPropagation();
});
}
}
Context menu event is correctly fired but I see only empty context menu.
I do no know how to (at this point) initialize context menu from ContextMenuService.
Hopefully it is possible.
No, you can't make a TemplateRef
directly in the typescript code. The closest you can get is something like this:
<div myDirective>div on which I want to display my dynamic context menu</div>
<my-prebuilt-context-menu></my-prebuilt-context-menu>
Or you could move my-prebuilt-context-menu
up to the root level and have all the instances of myDirective
reference it through a service.
If that looks like an approach you want to pursue, I can write up what my-prebuilt-context-menu
and myDirective
could look like.
Thanks for your help.
Unfortunately it cannot be done with using just a directive, as you say "can't make a TemplateRef directly in the typescript code".
I have now solved it by implementing a component.
It's not as 'nice' as it would be with a directive but it works.
Would be nice if in some future version we had an option to construct context in code, without html template.