如何使用“材料角度排序”对多个表进行排序?

时间:2019-02-21 18:25:36

标签: angular typescript

这是我的数组对象sortedData

enter image description here

在模板中可以看到*ngFor被应用在Contas中,每个Contas位置将是一个表:

<div *ngFor="let tabelaAnuncioContas of sortedData?.Contas; let a = index">
    <table id="tabelaAnunciosB2W" matSort (matSortChange)="sortData($event, a)">
         <tr>
            <th mat-sort-header="status">Status</th>
            <th>Miniatura</th>
            <th mat-sort-header="name">Título</th>
            <th mat-sort-header="qty">Quantidade</th>
            <th mat-sort-header="price">Valor</th>
            <th>Ações</th>
         </tr>
          ...

在我的TS中:

sortedData: any;

  sortData(sort: Sort) {
    const data = this.sortedData.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'status': return this.compare(a.status, b.status, isAsc);
        case 'name': return this.compare(a.name.toUpperCase(), b.name.toUpperCase(), isAsc);
        case 'qty': return this.compare(a.qty, b.qty, isAsc);
        case 'price': return this.compare(a.price, b.price, isAsc);
        case 'categories': return this.compare(a.categories.name.toUpperCase(), b.categories.name.toUpperCase(), isAsc)
        default: return 0;
      }
    });
  }

  compare(a: number | string, b: number | string, isAsc: boolean) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
  }

在我的控制台中,我收到以下错误消息:

  

错误TypeError:this.sortedData.slice不是函数

我正在http请求中设置此sortedData

this.sortedData = JSON.parse(JSON.stringify(res.body))

编辑:

更改为:

sortData(sort: Sort, indexTabela: number) {
    const data = this.anunciosB2w.Contas[indexTabela].Anuncio.products.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData.Contas[indexTabela].Anuncio.products = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'status': return this.compare(a.status, b.status, isAsc);
        case 'name': return this.compare(a.name.toUpperCase(), b.name.toUpperCase(), isAsc);
        case 'qty': return this.compare(a.qty, b.qty, isAsc);
        case 'price': return this.compare(a.price, b.price, isAsc);
        case 'categories': return this.compare(a.categories.name.toUpperCase(), b.categories.name.toUpperCase(), isAsc)
        default: return 0;
      }
    });
  }

现在排序有效,但是当我进行3次排序时,我的sortedData设置为null wtf

0 个答案:

没有答案