How to sort more than one table with Angular matSort

Asked

Viewed 108 times

0

I have the array object this.sortedData:

inserir a descrição da imagem aqui

An *ngFor is applied in the Accounts array, as you can see in the template, each Accounts position will be a table:

<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>
          ...

In my TS

@ViewChild(MatSort) sort: MatSort;


sortedData: any;

sortData(sort: Sort, indexTabela: number) {
   const data = this.anunciosB2w.Contas[indexTabela].Anuncio.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);
}

When I click on the template to order the following message is returned in the console:

ERROR Typeerror: data.Sort is not a Function

1 answer

0


I managed to change my function sortData to the following form:

  sortData(sort: Sort, indexTabela: number) {
    const data = this.anunciosB2w.Contas[indexTabela].Anuncio.products.slice();

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

  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.