【发布时间】:2019-02-28 19:50:01
【问题描述】:
table.component.html
当我点击标题时,该功能必须对所有列进行 ASC/DESC 排序。
<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
sortTable(param) 方法仅适用于 ASC,我无法为 DESC 再次单击同一个标题,因此在我单击另一个标题之前它保持不变。
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));
}
【问题讨论】:
-
@TheHeadRush 我看到了你的链接,它很有帮助......我搜索了所有内容。现在我解决了数字列的问题,正如您在我的编辑文档中看到的那样。 DESC排序的问题仍然存在,只是ASC,有什么建议吗?
-
当您调用
array.sort时附加reverse。使用提供的答案中的变量,例如objs.sort(compare).reverse()。 -
@TheHeadRush 我需要一些自动的东西,当是 ASC 或 DESC 时 +1/-1。我在那个链接上看到了一些东西,但没有任何效果......
-
@TheHeadRush 好的,完成,我现在将回答我自己的问题。谢谢!