4

I am using <p-table> and I have to implement sorting to its headers. I am doing as below:

HTML

<p-table [value]="documents">
        <ng-template pTemplate="header">
            <tr>
                <th [pSortableColumn]="">
                    File Name
                    <p-sortIcon [field]=""></p-sortIcon>
                </th>
               <th [pSortableColumn]="">
                    File Type
                    <p-sortIcon [field]=""></p-sortIcon>
                </th>
               <th [pSortableColumn]="">
                    File Date
                    <p-sortIcon [field]=""></p-sortIcon>
                </th>
            </tr>
        </ng-template>
    <ng-template pTemplate="body" let-doc>
        <tr>
            <td>
                {{doc.sName}}
            </td>

        <td>
                {{doc.sType}}
            </td>
        <td>
                {{doc.sDate}}
            </td>                
        </tr>
    </ng-template>
</p-table>

TS

ngOnInit(){
    //made a service call and got data for

this.documents=[{
   "sName":"Book",
   "sType":"PDF",
   "sDate":"20"
   },
   {
   "sName":"Book",
   "sType":"PDF",
   "sDate":"20"
   },
   {
   "sName":"Cook Book",
   "sType":"Text",
   "sDate":"20"
   },
   {
   "sName":"Book",
   "sType":"PDF",
   "sDate":"25-04"
   },
   {
   "sName":"File",
   "sType":"PDF",
   "sDate":"02-01"
   }]
}

I did used [pSortableColumn] and [field] in my code but I am not getting what value to pass to sort that particular field. The data is popping up correctly its only the sorting which I am missing on. Please guide me how to achieve the sorting of columns. Thanks

I cannot used <p-dataTable>

Anna
  • 1,669
  • 7
  • 38
  • 63

2 Answers2

10

Replace

<th [pSortableColumn]="">
    File Name
    <p-sortIcon [field]=""></p-sortIcon>
</th>

with

<th [pSortableColumn]="'sName'">
    File Name
    <p-sortIcon [field]=""></p-sortIcon>
</th>

in order do sort by sName for instance.

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
3

Just adding additional info to accepted answer from @Antikhippe, if some one needs it.

With the code example from accepted answer, the p-sort icon was not changing.

So using following code works.

<p-sortIcon [field]="'sName'"></p-sortIcon>
Kishor Prakash
  • 8,011
  • 12
  • 61
  • 92