Kunal Vijan
Kunal Vijan

Reputation: 435

When I am applying filters, why sorting is not working on table?

I have a filters on the data and sorting on table header. When I am applying for filters, sorting stops working. Both are working separately but once filter applied sorting stops working. Required assistance.

table-filter.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "tableFilter"
})

export class TableFilterPipe implements PipeTransform {
  transform(list: any[], filters: any) {
    const keys = Object.keys(filters).filter(key => filters[key]);
    const filterUser = (user: { [x: string]: any; }) =>
      keys.every(key => {
        if (key == "sdob") {
          return new Date(user["dob"]) >= new Date(filters[key]);
        } else if (key == "edob") {
          return new Date(filters[key]) >= new Date(user["dob"]);
        } else {
          return user[key] === filters[key];
        }
      });
    return keys.length ? list.filter(filterUser) : list;
  }
}

app.component.ts

sort(property: any) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    this.allUser.sort(function (a: { [x: string]: number; }, b: { [x: string]: number; }) {
      if (a[property] < b[property]) {
        return -1 * direction;        
      }
      else if (a[property] > b[property]) {
        return 1 * direction;
      }
      else {
        return 0;
      }
    });
  };

Live: https://angular-ivy-dubf37.stackblitz.io/

Upvotes: 0

Views: 609

Answers (1)

SeleM
SeleM

Reputation: 9638

It is a problem of sync between your TS and the generated DOM.

In your sort function, you should pass the filtered users (filteredUsers), since the problem here is even after filtering (DOM part), it keeps sorting the whole users' list (business logic part) and that's not the intended behavior:

(click)="sort('first_name', filteredUsers)">First Name</th>
(click)="sort('last_name', filteredUsers)">Last Name</th>

And in the TS part become:

  sort(property: any, filteredUsers) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    filteredUsers.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    ) {
      if (a[property] < b[property]) {
        return -1 * direction;
      } else if (a[property] > b[property]) {
        return 1 * direction;
      } else {
        return 0;
      }
    });
  }

DEMO

Upvotes: 1

Related Questions