【问题标题】:Open the context menu by PrimeNG from code Angular 2通过 PrimeNG 从代码 Angular 2 打开上下文菜单
【发布时间】:2017-09-21 06:38:12
【问题描述】:

我需要通过 PrimeNG 在table 中使用按钮和右键单击打开context menu。我在component 中找到了用于打开菜单的“切换”和“显示”方法,但它没有打开。当我调用该方法时,我为菜单设置了新位置,但属性“显示”仍然有一个“无”,但有一个新位置。为了从 typescript 的模板中获取组件“contextMenu”,我使用了 Angular 的 ViewChild。

【问题讨论】:

  • PrimeFaces != PrimeNG(虽然它在 PrimeFaces 的“网站”上)。请记住这一点。
  • 我指的是名为 PrimeFaces 的开发团队,谢谢!
  • 我也需要同样的。在 Typescript 代码中显示和隐藏...
  • 这方面有什么更新吗?

标签: angular typescript primeng


【解决方案1】:

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

模板中的 ContextMenu:

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

在您的按钮上:(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);
    }
  }

cm 是你的ContextMenu

@ViewChild("cm") cm:ContextMenu;

或者,对于这个用例,它存在 ContextMenu 的替代方案:PrimeNG's tiered menu

【讨论】:

    【解决方案2】:

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

    <p-contextMenu #cm [model]="items"></p-contextMenu>
    
    <button (click)="cm.show($event);$event.stopPropagation();">Show context</button>
    

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

    (click)="showContext(cm, $event)"
    

    在 TS 中:

    showContext(cm: ContextMenu, event :MouseEvent) {
      cm.show(event);
      event.stopPropagation();
    }
    

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

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

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

    【讨论】:

    • 这解决了我在以编程方式调用时上下文菜单出现在页面错误位置的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多