Raghav
Raghav

Reputation: 1229

How to disable sorting for selected columns in PrimeNG table?

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?

Upvotes: 6

Views: 4955

Answers (1)

Raghav
Raghav

Reputation: 1229

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"

Upvotes: 6

Related Questions