Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So I have a html table where the rows and columns are interpolated from my User like his name, last login date, etc.

Earlier we used Prime NG's customSort function but now we are eliminating those so I need to make my own sorting function.

Can I make it withOUT using AngularJS, JavaScript, Bootstrap, Angular Material or any 3rd party thing? If yes, how?

I spent 2 days just googling but I didn't find any solution that doesn't include one of the mentioned ways above.

My HTML table at the moment:

<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="normalColumn"> {{ item.firstname }}</span>
      </td>
      <td>
        <span class="normalColumn"> {{ item.lastname }}</span>
      </td>
      <td>
        <span class="normalColumn"> {{ item.email }}</span>
      </td>
      <td>
        <span class="normalColumn" *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>

I know that I should make a function and use it on the headers with Angular's onClick, but I don't know how to do more. Should I use different sorting functions on each columns? Or how should I write it?

Thank you in advance!

like image 602
kameholic1582 Avatar asked Oct 13 '25 01:10

kameholic1582


1 Answers

A very simple implementation would involve:

making each column header clickable

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

then sorting your items list by that property in the controller

sort(colName) {
    this.items.sort((a, b) => a[colName] > b[colName] ? 1 : a[colName] < b[colName] ? -1 : 0)
}
like image 110
paul Avatar answered Oct 14 '25 14:10

paul