在不使用材料的情况下对 Angular 表进行排序,只是排序方法?

编程入门 行业动态 更新时间:2024-10-11 15:13:44
本文介绍了在不使用材料的情况下对 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 表进行排序,只是排序方法?

本文发布于:2023-11-11 08:55:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   材料   方法   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!