Search code examples
angulartypescriptprimengprimeng-datatableprimeng-turbotable

How to select multiple rows in Angular using primeng table?


I have a primeng table. I want to select multiple rows .

html:

<p-contextMenu #cm [model]="items"></p-contextMenu>
<p-table [columns]="columns" [value]="values" [(contextMenuSelection)]="selectedProduct" [contextMenu]="cm" dataKey="tradeId" [rowHover]=true
     selectionMode="multiple" [(selection)]="selectedProducts2"
     >
<ng-template pTemplate="header" let-columns>
<tr>
  <th pSortableColumn *ngFor="let col of getKeys(columns)" pReorderableColumn pResizableColumn>
    {{col}}
  </th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-block let-columns="columns" let-rowIndex="rowIndex">
 <tr [pSelectableRow]="block" [pSelectableRowIndex]="rowIndex">
  <td *ngFor="let col of getKeys(columns)">
    {{block[col]}}
  </td>
</tr>
</ng-template>

typescript

import {Component, OnInit, Input, SimpleChanges} from '@angular/core';
import {MenuItem} from "primeng/api";

@Component({
selector: 'app-data-table',
templateUrl: './data-table.component.html',
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {

@Input() public omsBlockList : OmsBlock[] =[];
@Input() public selectedEntity: any ='';
@Input() public entityData : any;
    
selectedProduct=OmsBlock[];

selectedProducts2=OmsBlock[];

omsBlocks: OmsBlock[]=[];
items: MenuItem[]=[];
_entity=new Map<String,String>();
columns: any;
cols:any[]=[];
entityfieldMap: any=new Map();
exportColumns: any[];

constructor() { 
this.selectedProduct={} as OmsBlock;
}

ngOnInit() {
  this.exportColumns=this.cols.map(col => ({title: col.header, datakey: col.field}));
}
getKeys(map):string[]{ 
 if(map!=null){
 return Array.from(map.values());
 }
}

ngOnChanges(changes:SimpleChanges){
 this._entityData=new Map<String,String>();
 for(var val of this.entityData[this.selectedEntity]["fields"]){
  this._entityData.set(val["displayName"], val["fieldName"]);
  }
   this.columns.this._entityData;
}

}

On selecting a single row, all rows are getting selected. I want to select rows using without metakey and on click of each row, that row must be selected. On selection of one row multiple rows are getting selected. I am referring same code from this site-> https://primefaces.org/primeng/showcase/#/table/selection Any mistakes I am making?


Solution

  • I guess something is wrong with your

    [dataKey]="tradeId"
    

    Is tradeId unique for each row? I played with it a bit, it works fine with the [datakey]="code", you can check it here https://stackblitz.com/edit/primeng-tableselection-demo-9t5cyt?file=src%2Fapp%2Fapp.component.ts