How can I set the default sort order on the primeng datatable?
If you sort on multiple columns, you can parameter the initial sorting with (working on deprecated DataTable and on the current PrimeNG Table Component):
[multiSortMeta]="[{field: 'state', order: -1}, {field: 'displayName', order: 1}]"
Example with Table component (PrimeNG 7+):
<p-table [value]="products2" sortMode="multiple" [multiSortMeta]="[{field: 'code', order: -1}, {field: 'name', order: 1}, {field: 'category', order: -1}]">
<ng-template pTemplate="header">
<tr>
<th pSortableColumn="code">Code <p-sortIcon field="code"></p-sortIcon></th>
<th pSortableColumn="name">Name <p-sortIcon field="name"></p-sortIcon></th>
<th pSortableColumn="category">Category <p-sortIcon field="category"></p-sortIcon></th>
<th pSortableColumn="quantity">Quantity <p-sortIcon field="quantity"></p-sortIcon></th>
<th pSortableColumn="price">Price <p-sortIcon field="price"></p-sortIcon></th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-product>
<tr>
<td>{{product.code}}</td>
<td>{{product.name}}</td>
<td>{{product.category}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price | currency: 'USD'}}</td>
</tr>
</ng-template>
</p-table>
I figured it out. These two attributes should be added:
sortField="userName" [sortOrder]="-1"
The sortField matches the column name and the sortOrder can be either 1 for ascending and -1 for descending.
Here's the working solution:
<p-dataTable [value]="webUserSummaryList" [rows]="10" reorderableColumns="true" sortField="userName" sortOrder="-1">
<p-column field="userName" header="Username" [filter]="true" [sortable]="true"></p-column>
<p-column field="emailAddress" header="Email" [filter]="true" [sortable]="true"></p-column>
<p-column field="firstName" header="First Name" [filter]="true" [sortable]="true"></p-column>
<p-column field="lastName" header="Last Name" [filter]="true" filterMatchMode="contains" [sortable]="true"></p-column>