[Fixed] Get column index from context menu event in primeng table

Issue

I have created a p-table with certain rows and columns and intend to implement context menu on right mouse button click. For that I have modified my app.component.html by adding the following code:

<p-table #dt [contextMenu]="cm" (onContextMenuSelect)="onContextMenuSelect($event,cm)">
<ng-template pTemplate="body" let-row let-columns="colData">
<tr [pSelectableRow]="row" [pContextMenuRow]="row" ng-mousedown="handleClick($event)" >
            <td pEditableColumn style= "height:34px;" *ngFor="let col of colData">
                <p-cellEditor>
...
</td>
        </tr>
    </ng-template>
</p-table>
</div>

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

I am able to successfully get the RMB menu items on right mouse button click. However I intend to do further processing inside the onContextMenuSelect(event,cm) function on the column on which the rmb mouse button is clicked. Is there any way I can find the column index on which the user has performed the RMB click?

Solution

Better late than never… but, at least, for the records.

Here is what I do:

<td *ngFor="let col of columns" **[pContextMenuRow]="{col: col, data: this}"**>
  <span *ngIf="!col.template && !col.component" class="p-text-bold p-ml-2">{{url[col.field]}}</span>
  <span *ngIf="col.template && !col.component" class="p-text-bold p-ml-2">{{col.template(myRowData[col.field])}}</span>
  <ng-container *ngIf="col.component">
    <ng-container *ngComponentOutlet="col.component; injector: getInjector(col.field);">
    </ng-container>
  </ng-container>
</td>

That way, you get information you need in the contextMenu command callback in your table component.
In my case, columns are dynamically added. So I can get the "field" (column) selected from col.
You can also add [pContextMenuRow] on the row, and handle the event depending on the context.

Leave a Reply

(*) Required, Your email will not be published