TableSortController
Purpose
Allow sorting of tables by clicking on column headers.
Actions
| Action | Purpose |
|---|---|
- | - |
Targets
| Target | Purpose | Default |
|---|---|---|
- | - | - |
Classes
| Class | Purpose | Default |
|---|---|---|
- | - | - |
Values
| Value | Type | Description | Default |
|---|---|---|---|
startSort (Optional) | Number | The index (zero indexed) of the column to sort on load. | No sort |
Events
| Event | When | Dispatched on | event.detail |
|---|---|---|---|
- | - | - | - |
Side Effects
Installs click event listeners on all column headers.
How to Use
This is a fire-and-forget controller, there are no actions, targets or events to worry about. Just install it on your table and forget about it.
The controller expects a well-formed table, including a <thead> with one row of header cells, and <tbody> with all of your table data.
Once the controller is installed, users can sort table data by clicking on <th> cells in the table's header.
If you want to mark a column as unsortable, add data-sortable="false" to the <th> element for that column.
If you want to sort a column by some other value than its text content, add data-sort-value="something-else" to each cell in that column.
i.e.
<tr>
<td>Sally</td>
<td>21</td>
<td>sally@example.com</td>
<td data-sort-value="2021-01-19">January 19th, 2021</td>
</tr>
<tr>
<td>Trevor</td>
<td>45</td>
<td>trevor@example.com</td>
<td data-sort-value="2020-02-18">February 18th, 2020</td>
</tr>
If startSortValue is set, the table will be sorted on load, otherwise the table will stay as it loaded until a user clicks on a column heading.
You can also set data-sort-bottom and data-sort-top attributes on <tr>s to pin a row to the top or bottom of the table, i.e.
<tr data-sort-top="true">
<td colspan="4">
This row is always at the top
</td>
</tr>
<tr>
<td>Sally</td>
<td>21</td>
<td>sally@example.com</td>
<td>January 19th, 2021</td>
</tr>
<tr data-sort-bottom="true">
<td colspan="4">
This row is always at the bottom
</td>
</tr>
Demo
Notes & Limitations
- This controller cannot sort tables with inconsistent colspans. If your table has
<th>and<td>with the same colspans, everything should work as expected, everything else is undefined. - This controller also cannot sort tables with rowspans.
- When the table is sorted, rows are removed from the DOM and re-inserted into their new position - any custom properties or installed event listeners on the
<tr>and<td>elements may be lost.