问题
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));
}
回答1:
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:
<!-- Returns array ordered by value of property -->
<p>{{ deepObj | orderBy: 'amount' }}</p>
<!-- Output: [{id: 3, ...}, {id: 4, ...}, {id: 2, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-amount' }}</p>
<!-- Output: [{id: 1, ...}, {id: 2, ...}, {id: 4, ...}, {id: 3, ...}] -->
回答2:
I had problems with the reverse Sort so I did like this and it works!
export class DynamicTableComponent implements OnInit {
@Input()
users = [];
@Input()
columns: string[];
direction = false;
sortTable(param) {
this.direction = !this.direction;
const compare = (a, b) => {
if (!a[param] && !b[param]) {
return 0;
} else if (a[param] && !b[param]) {
return -1;
} else if (!a[param] && b[param]) {
return 1;
} else {
const value1 = a[param].toString().toUpperCase(); // ignore upper and lowercase
const value2 = b[param].toString().toUpperCase(); // ignore upper and lowercase
if (value1 < value2) {
return !this.direction ? -1 : 1;
} else if (value1 > value2) {
return !this.direction ? 1 : -1;
} else {
return 0;
}
}
};
return this.users.sort(compare);
//this.users = MYITEMS
}
来源:https://stackoverflow.com/questions/54933222/sorting-angular-table-without-using-materials-just-sort-method