I am using primeNg <p-table>
. I want to implement sorting of data. What I did is below
sort.HTML
<p-table [columns]="cols" [value]="documents">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field">
{{col.header}}
<p-sortIcon [field]="col.field"></p-sortIcon>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-doc>
<tr>
<td>
{{doc.sName}}
</td>
<td>
{{doc.sYear}}
</td>
<td>
{{doc.sAge}}
</td>
<td>
{{doc.sColor}}
</td>
</tr>
</ng-template>
</p-table>
sort.ts
this.cols = [
{ field: 'name', header: 'Name' },
{ field: 'year', header: 'Year' },
{ field: 'age', header: 'Age' },
{ field: 'color', header: 'Color' }
];
ngOnInit(){
//made a service call and got data for
this.documents=[{
"sName":"Jhon",
"sYear":"1994",
"sAge":"20",
"sColor":"Red"
},
{
"sName":"Sam",
"sYear":"1996",
"sAge":"25",
"sColor":"Red"
},
{
"sName":"Anna",
"sYear":"1991",
"sAge":"21",
"sColor":"Green"
},
{
"sName":"Jhon",
"sYear":"1999",
"sAge":"25",
"sColor":"Blue"
},
{
"sName":"Betty",
"sYear":"1993",
"sAge":"35",
"sColor":"Red"
}]
}
As of now only Name
field is getting sorted, how can I implement sorting in other columns as well? I used [pSortableColumn]
but columns are not getting sorted, I am missing out of somepoint. Can you please guide me where I am wrong?
PS: I cannot used <p-dataTable>
.
For Sorting with Turbo table / p-table with fixed column try below code
<p-table #dt [value]="data">
<ng-template pTemplate="header">
<tr>
<th [pSortableColumn]="'Name'">Name
<p-sortIcon [field]="'Name'"></p-sortIcon>
</th>
<th [pSortableColumn]="'Age'">Age
<p-sortIcon [field]="'Age'"></p-sortIcon>
</th>
<th [pSortableColumn]="'Height'">Height
<p-sortIcon [field]="'Height'"></p-sortIcon>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-col>
<tr>
<td>{{col.Name}}</td>
<td>{{col.Age}}</td>
<td>{{col.Height}}</td>
</tr>
</ng-template>
</p-table>