table.component.html
When I click on the Header, the function have to sort ASC/DESC all the column.
<table>
<tr>
<th *ngFor="let col of columns" (click)="sortTable(col)">{{col}}</th>
</tr>
<tr *ngFor="let user of users">
<td *ngFor="let col of columns">{{user[col]}}</td>
</tr>
</table>
table.component.ts
The method sortTable(param)
work just ASC and I can't click on the same Header again for the DESC so it remain the same until I click on another Header.
export class DynamicTableComponent implements OnInit {
@Input()
users = [];
@Input()
columns: string[];
constructor() { }
sortTable(param) {
this.users.sort((a, b) =>
(a[param] > b[param]) ? 1 :
((b[param] > a[param]) ? -1 :
0));
}
I had problems with the reverse Sort so I did like this and it works!
Have you considered using existing pipes for sorting instead of writing your own? EG: https://github.com/danrevah/ngx-pipes
And more directly, this: https://github.com/danrevah/ngx-pipes#orderby
Using that package you only then need to manage click to set a variable to determine the orderby and whether it is ASC or DESC, as denoted by the prefix.
EG from Docs: