如何在没有第 3 方的情况下使用 Angular/Typescript 对 HTML table 进行排序?

How can I sort HTML table using Angular/Typescript without 3rd party?

所以我有一个 html table,其中的行和列是从我的用户中插入的,例如他的姓名、上次登录日期等。

之前我们使用 Prime NG 的 customSort 功能,但现在我们正在取消这些功能,所以我需要制作自己的排序功能。

我可以不使用 AngularJS、JavaScript、Bootstrap、Angular Material 或任何第 3 方的东西吗?如果是,如何?

我花了 2 天时间在谷歌上搜索,但没有找到任何不包含上述方法之一的解决方案。

我现在的HTMLtable:

<table class="table" scrollHeight="calc(100vh - 170px)">
    <tr>
      <th class="tableHeader" *ngFor="let col of tableHeaders">
        {{ col.header | translate }}
        <my-icon
          *ngIf="col.field !== 'access_level'"
          [icon]="Icon.sort"
        ></my-icon>
      </th>
    </tr>
    <tr *ngFor="let item of items">
      <td>
        <span class="normalColoumn"> {{ item.firstname }}</span>
      </td>
      <td>
        <span class="normalColoumn"> {{ item.lastname }}</span>
      </td>
      <td>
        <span class="normalColoumn"> {{ item.email }}</span>
      </td>
      <td>
        <span class="normalColoumn" *ngFor="let roleId of item.roleIds">
          {{ getUserRole(roleId).name }}</span
        >
      </td>
      <td>
        <span class="left">
          {{
            item.lastLoginDate
              ? (item.lastLoginDate | fromnow)
              : ('USER_MANAGEMENT.UNKNOWN_LAST_LOGIN' | translate)
          }}
        </span>
        <span class="only-show-on-hover">
          <my-icon [icon]="Icon.edit"></my-icon>
          <my-icon [icon]="Icon.password"></my-icon>
          <my-icon [icon]="Icon.delete"></my-icon>
        </span>
      </td>
    </tr>
  </table>

我知道我应该制作一个函数并在 headers 上使用 Angular 的 onClick,但我不知道如何做更多。我应该在每个列上使用不同的排序功能吗?或者应该怎么写?

提前致谢!

一个非常简单的实现将涉及:

使每列 header 可点击

<th class="tableHeader" *ngFor="let col of tableHeaders" (click)="sort(col.propertyName)">

然后根据控制器中的 属性 对 items 列表进行排序

sort(colName) { this.items.sort((a, b) => a[colName] > b[colName] ? 1 : a[colName] < b[colName] ? -1 : 0) }

Paul 用他的函数正确回答了它,但我想对其进行一些更改以切换输出。 该函数仅return按升序输出。

这里有一个切换升序和降序的建议-

<th class="tableHeader" *ngFor="let col of tableHeaders" (click)="sort(col.propertyName, booleanValue)">

Declare a boolean variable into your TS file as

    booleanValue: any = false;

Then use this function in TS file

sortFunction(colName, boolean) {
    if (boolean == true){
        this.data.sort((a, b) => a[colName] < b[colName] ? 1 : a[colName] > b[colName] ? -1 : 0)
        this.booleanValue = !this.booleanValue
    }
    else{
        this.data.sort((a, b) => a[colName] > b[colName] ? 1 : a[colName] < b[colName] ? -1 : 0)
        this.booleanValue = !this.booleanValue
    }
}

Now you can have a sorting in Ascending and Descending order. Thank you.