Reputation: 53786
I'm attempting to create a sort a basic table using Angular.
To setup the table I use:
<table id="tableSortExample" mdbTable class="z-depth-1">
<thead>
<tr>
<th (click)="sort('One')">One</th>
<th (click)="sort('Two')">Two</th>
<th (click)="sort('Three')">Three</th>
<th (click)="sort('Four')">Four</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let el of elements; let i = index">
<th scope="row">{{el.id}}</th>
<td>{{el.first}}</td>
<td>{{el.last}}</td>
<td>{{el.handle}}</td>
</tr>
</tbody>
</table>
and then define in the component:
sort(colName) {
console.log('sort clicked : ' + colName);
this.elements.sort((a, b) => a[colName] > b[colName] ? 1 : a[colName] < b[colName] ? -1 : 0)
}
// tslint:disable-next-line:typedef
ngOnInit() {
for (let i = 1; i <= 11; i++) {
this.elements.push({
id: i,
first: 'test',
last: 'Name ' + i,
handle: 'Handle ' + i
});
}
}
On opening the page that contains the HTML the table is rendered :
But clicking the column headers does not apply the sort.
The function sort is fired on click as can see messages printed to the log:
console.log('sort clicked : ' + colName);
I'm attempting to work from a previously answered question but it seems I've missed a step or not understood something.
How to enable sort of the columns ?
Upvotes: 0
Views: 51
Reputation: 1247
The keys in the elements
array are: id
, first
, last
, and handle
Replace the arguments in the sort
functions called.
<th (click)="sort('id')">One</th>
<th (click)="sort('first')">Two</th>
<th (click)="sort('last')">Three</th>
<th (click)="sort('handle')">Four</th>
Upvotes: 1