PrimeNg Context Menu Example
Today, I want to talk about PrimeNg ContextMenu. Context Menu property is very usefull for PrimeNg table operations. Let’s make a PrimeNg Context Menu Example. First we must prepare the html code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<p-contextMenu #cm [model]="selectHeaderMenu" appendTo="header"></p-contextMenu> <p-table #excelTableCustom id="excelTableCustom" [scrollable]="true" [style]="{width:'1000px;'}" [(contextMenuSelection)]="selectedHeader" [contextMenu]="cm" [value]="customExcelData" [paginator]="true" [rows]="10" [totalRecords]="customExcelData.length" > <ng-template pTemplate="header" let-colData> <tr> <th *ngFor="let col of excelHeadersDynamic" style="width:100px;"> {{col.value}} </th> </tr> <tr> <th [pContextMenuRow]="map" *ngFor="let map of excelHeadersMap" style="width:100px;"> {{map.value}} </th> </tr> </ng-template> <ng-template pTemplate="body" let-rowData> <tr> <td *ngFor="let col of excelHeadersDynamic" style="width:100px;"> {{rowData[col.order].value}} </td> </tr> </ng-template> </p-table> |
We connect the table to contextmenu with [contextMenu]=”cm” in p-table. In this example, our goal is to change the headers with right click. We will add this code to typescript file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
customExcelData: IExcelTableData[][] = []; selectedHeader: IExcelTableData = {}; excelHeadersDynamic: IExcelTableData[] = []; excelHeadersMap: IExcelTableData[] = []; this.selectHeaderMenu = [ {label: 'Product Value', command: (event => this.excelChoose(1))}, {label: 'Price Per Unit', command: (event => this.excelChoose(2))}, {label: 'Sales Amount', command: (event => this.excelChoose(3))}, ]; this.excelHeadersDynamic = []; this.excelHeadersMap = []; excelChoose(choice: number) { if (choice=== 0) { this.selectedHeader.value = this.selectHeaderMenu[0].label; else if (choice === 1) this.selectedHeader.value = this.selectHeaderMenu[1].label; } } else { this.selectedHeader.value = this.selectHeaderMenu[choice+ 2].label; } } export interface IExcelTableData { value?: string; order?: number; } export class ExcelTableData implements IExcelTableData { constructor( public value?: string, public order?: number, ) {} |
We can write the event code to the “this.selectHeaderMenu “. Then we can change the header in the function excelChoose. That’s just all. It is very easy and simple to change headers in PrimeNg ContextMenu with this example. If you want to see another post about PrimeNg table, have a look to this PrimeNg Table
Do you have an example for adjusting the width of the ContextMenu to accommodate longer entries?