从代码Angular 2中打开PrimeNG的上下文菜单

Dan*_*zov 6 typescript primeng angular

我需要使用按钮并使用右键单击表格中的PrimeNG 打开上下文菜单.我发现方法'切换'和'显示'到组件中打开菜单,但它没有打开.当我调用方法时,我为菜单设置新位置,但属性'display'仍然有'none',但是有一个新位置.为了从typescript中的模板获取组件"contextMenu",我使用Angular的ViewChild.

小智 12

在引用局部变量(本例中为 cm)的按钮/span/div/等上添加上下文菜单和单击事件,并调用显示或切换函数。

<p-contextMenu #cm [model]="items"></p-contextMenu>

<button (click)="cm.show($event);$event.stopPropagation();">Show context</button>
Run Code Online (Sandbox Code Playgroud)

请随意将其传递给将处理它的函数:

(click)="showContext(cm, $event)"
Run Code Online (Sandbox Code Playgroud)

在 TS 中:

showContext(cm: ContextMenu, event :MouseEvent) {
  cm.show(event);
  event.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)

似乎必要的最重要的事情(至少在 PrimeNG 7 上)是 event.stopPropagation()。如果没有它,如果您查看 DOM,您将看到上下文菜单对 show() 事件做出反应,但显示保持为无。

另一件重要的事情是在 show() 中传递鼠标事件,这使得上下文菜单出现在光标所在的位置,否则它出现在页面的其他位置。

如果尝试纯粹通过代码调用显示/切换并使用 ViewChild 而没有发生单击事件,您可以尝试手动编辑样式并将 display:none 更改为 display:block (如 Y. Tarion 的评论中所述) )


Y. *_*ion 2

您可以通过编程方式打开 contextMenu PrimeNG,但这有点棘手。

您模板中的上下文菜单:

<p-contextMenu #cm [global]="true" [model]="items"></p-contextMenu>
Run Code Online (Sandbox Code Playgroud)

在你的按钮上:(click)="toggle($event)"

在您的打字稿上,这里是切换方法的示例:

  toggle(event){
    if(!this.cm.containerViewChild.nativeElement.style.display ||
      this.cm.containerViewChild.nativeElement.style.display == 'none') {
      //Open contextual menu
      setTimeout(() => {
        this.cm.position(event);
        this.cm.containerViewChild.nativeElement.style.display = 'block';
        this.cm.containerViewChild.nativeElement.style.visiblility = 'visible';
      }, 0);
    }else{
      //close contextual menu
      setTimeout(() => {
        this.cm.containerViewChild.nativeElement.style.display = 'none';
      }, 0);
    }
  }
Run Code Online (Sandbox Code Playgroud)

cm你在哪里ContextMenu

@ViewChild("cm") cm:ContextMenu;
Run Code Online (Sandbox Code Playgroud)

或者,对于此用例,上下文菜单中有一个替代方案:PrimeNG 的分层菜单