PrimgNg: <p-table> column sorting

Anna picture Anna · Jun 28, 2018 · Viewed 7.5k times · Source

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>

Answer

Antikhippe picture Antikhippe · Jun 28, 2018

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.