【问题标题】:When I am applying filters, why sorting is not working on table?当我应用过滤器时,为什么排序在表格上不起作用?
【发布时间】:2021-04-11 23:44:29
【问题描述】:

我有一个数据过滤器和表格标题排序。当我申请过滤器时,排序停止工作。两者都单独工作,但一旦应用过滤器排序就会停止工作。 需要帮助。

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;
      }
    });
  };

直播:https://angular-ivy-dubf37.stackblitz.io/

【问题讨论】:

    标签: javascript angular typescript sorting filter


    【解决方案1】:

    这是你的 TS 和生成的 DOM 同步的问题。

    在您的sort 函数中,您应该传递过滤后的用户(filteredUsers),因为这里的问题是即使在过滤后(DOM 部分),它仍然在排序整个用户列表(业务逻辑部分),这不是预期的行为:

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

    在TS部分变成:

      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

    【讨论】:

    • 你能帮我解决另一个问题吗?当我过滤我的总记录数时正在更新,但有多少适用和有多少不适用没有更新。你能也调查一下吗?
    • 我有一个 getCounts 函数来计算计数。
    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2011-05-06
    • 2023-03-13
    相关资源
    最近更新 更多