How to disable sorting for selected columns in PrimeNG table?
Asked Answered
C

1

6

I'm trying to disable sorting of selected columns based on Boolean value in PrimeNG table. Below is my columns array

cols = [
    { field: 'name', header: 'Name', sort: true },
    { field: 'age', header: 'Age', sort: true },
    { field: 'gender', header: 'Gender', sort: false },
    { field: 'status', header: 'Status', sort: false }
  ];

Some of the columns having sort value as false and I need to disable those columns from sorting.

<p-table [columns]="cols" [value]="persons" [resizableColumns]="true" sortField="name" sortMode="single">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th pResizableColumn  *ngFor="let col of columns" [pSortableColumn]="col.field" [pSortableColumnDisabled]="col.field === 'name' || col.field === 'age'">
                <div class="tb-heading">{{col.header}}</div>
                <div class="sort-icons-container">
                </div>
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr [pSelectableRow]="rowData">
            <td *ngFor="let col of columns">
                {{rowData[col.field]}}  
            </td>
        </tr>
    </ng-template>
</p-table> 

I can use above code for disabling columns i.e., name and age by using pSortableColumnDisabled but I don't want to hardcode the column names like above as these columns will be passed dynamically by parent component.

Is there any way to disable the columns based on respective sort Boolean value?

Cumae answered 20/5, 2022 at 14:2 Comment(0)
C
6

After spending sometime on internet found the solution for above problem https://embed.plnkr.co/egBhS1DJhY2Ud1ByfGBp/

Changed the hardcoded condition from

[pSortableColumn]="col.field" [pSortableColumnDisabled]="col.field === 'name' || col.field === 'age'"

to

[pSortableColumnDisabled]="!col.sort ? true : false"
Cumae answered 20/5, 2022 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.