本文介绍了在不使用材料的情况下对 Angular 表进行排序,只是排序方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
tableponent.html
tableponent.html
当我点击标题时,该功能必须对所有列进行 ASC/DESC 排序.
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>tableponent.ts
tableponent.ts
sortTable(param) 方法仅适用于 ASC,我无法再次单击 DESC 的相同标题,因此在单击另一个标题之前它保持不变.
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!
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 }更多推荐
在不使用材料的情况下对 Angular 表进行排序,只是排序方法?
发布评论