Search code examples
angularprimengprimeng-datatable

How to set the default sort order of primeng table depending on observable value


I have p-table with sortable columns. However, initially I want the table to be sorted by a specific column, I use sortFiled for that. But this column is not known till run-time. Here is a snippet of the table:

<p-table [value]="offers" sortField="totalPrice">
    <ng-template pTemplate="header">
       <tr>
          <th pSortableColumn="shopName">Name
              <p-sortIcon field="shopName"></p-sortIcon>
          </th>
          <th pSortableColumn="unitPrice">Unit price
              <p-sortIcon field="unitPrice"></p-sortIcon>
          </th>
          <th pSortableColumn="totalPrice">Total price
              <p-sortIcon field="totalPrice"></p-sortIcon>
          </th>
       </tr>
   </ng-template>
   <ng-template pTemplate="body"> .... </ng-template>
</p-table>

I need to specify the column depending on the value of an observable, something like the following but that doesnt seem to work.

 <p-table [value]="offers" sortField="(isRelventPrice$ | async)? totalPrice : unitPrice">

Any help would be appreciated thank you.


Solution

  • sortField is the current selected filtered column and will be updated in case of any value change.

    you can set it as simple string

    <p-table [value]="offers" sortField="totalPrice">...<p-table>
    

    in case of data binding you need to use curly brackets []

    <p-table [value]="offers" [sortField]="totalPriceValue">...<p-table>
    

    and for you case isRelventPrice$ this will work

     <p-table 
        [value]="offers" [sortField]="(isRelventPrice$ | async)? 'totalPrice' : 'unitPrice'">
    ....
    </p-table>
    

    check this demo 🚀

    angular binding syntax