How to use Primeng Menu with command and parameters in DataTable?

Gabriel Costa picture Gabriel Costa · Nov 29, 2017 · Viewed 16k times · Source

MenuItem of primeng has a parameter called command that is a function to be executed when its item is clicked. One example of using this is provided in https://www.primefaces.org/primeng/#/steps to give feedback to user.

command: (event: any) => {
                this.activeIndex = 0;
                this.msgs.length = 0;
                this.msgs.push({severity:'info', summary:'First Step', detail: event.item.label});
            }

However, I want to use the MenuItem as a column of my Primeng DataTable, like this.

enter image description here

And for this I need to use my menu this way:

<p-column>
  <ng-template let-item="rowData"
      <p-menu #menu popup="popup" [model]="items"></p-menu>
      <button type="button" pButton icon="fa fa-list" label="Show" (click)="menu.toggle($event)"></button>
  </ng-template>
</p-column>

To get "item" and the row that I'm clicking and other kind of data.

Using a buttom I can pass item and other data through onClick, but for this I need to create one column for each buttom. And to solve that I want to use Menu with MenuItem from primeng.

The problem is that I can't find any examples passing parameters through a command in MenuItem and I'm not find a way to do it.

How can I accomplish that using MenuItem with DataTable?

If that is not possible, how can I accomplish the same results?

Answer

sabithpocker picture sabithpocker · Mar 23, 2018

You can have a function that takes rowData and returns contextual MenuItem[]

<p-column>
  <ng-template let-item="rowData"
      <p-menu #menu popup="popup" [model]="getMenuItemsForItem(item)"></p-menu>
      <button type="button" pButton icon="fa fa-list" label="Show" (click)="menu.toggle($event)"></button>
  </ng-template>
</p-column>

  getMenuItemsForItem(item: MyItem): MenuItem[] {
    const context = item;
    return [
      { label: 'Label1', icon: 'fa-plus', command: e => this.takeAction(e, context) }
    ]
  }

UPDATE

[model]="getMenuItemsForItem(item)"

can cause performance issues, should be using a binding to an object instead.

[model]="menuItems[item.uniqueKey]"

and then set menuItems object with menu items for each item.