首页 > 解决方案 > 使用指令对 *ngFor 中使用的对象数组进行排序

问题描述

使用 Angular,我创建了一个带有排序指令的表,该指令根据单击的标题对表进行排序。但是,如果输入数据有任何空值,排序指令将无法正常工作。

这是我在指令中的排序功能:

  sortArray (): Array<any> {
    let tempArray: Array<any> = this.data;
    tempArray.sort((a, b) => {
      let aKey = a[this.key];
        let str1: string = a[this.key].toLowerCase();
        let str2: string = b[this.key].toLowerCase();
        if (this.toggleSort) {
          if (str1 < str2) {
            return -1;
          }
          if (str1 > str2) {
            return 1;
          }
        }
        else {
          if (str1 > str2) {
            return -1;
          }
          if (str1 < str2) {
            return 1;
          }
        }
      return 0;
    });
    return tempArray;
  }

我怎样才能让它对空值起作用?

为这个问题附上了一个 Stackblitz。

标签: angular

解决方案


sortArray (): Array<any> {
    let tempArray: Array<any> = this.data;
    tempArray.sort((a, b) => {
      let aKey = a[this.key];
        let str1: string = a[this.key].toLowerCase();
        let str2: string = b[this.key].toLowerCase();
        if (this.toggleSort) {
          if (!str1 && !str2) {
            return 0;
          } else if (!str1) {
            return 1;
          } else if (!str2) {
            return -1;
          }

          //rest of your logic if neither is null
          if (str1 < str2) {
            return -1;
          }
          if (str1 > str2) {
            return 1;
          }
        }
        else {
          if (str1 > str2) {
            return -1;
          }
          if (str1 < str2) {
            return 1;
          }
        }
      return 0;
    });
    return tempArray;
  }

推荐阅读