1

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.

Lossan
  • 411
  • 1
  • 8
  • 16
  • 1
    sortField requires a string and it looks like you're passing in variables. Will it work if you make the totalPrice and unitPrice as strings? `` – Jeremy Dec 11 '20 at 23:06
  • 1
    this will solve your problem `[sortField]="(isRelventPrice$ | async)? 'totalPrice' : 'unitPrice'"` – Muhammed Albarmavi Dec 14 '20 at 00:49

1 Answers1

1

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

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • I was playing around with the demo but when I specify for the [sortField] category, quantity or price the order is not correct. – edjm Sep 15 '22 at 17:10