Skip to main content

Grouping an Angular DataTable by Same Value

In my code, I have a JSON list which I fetch a data using fromFetch(). I can get the data and group it on the console by categoryId. The problem is, I can not group them on the datatable and I want to group the elements by categoryId. I couldn't find a solution that was appropriate for my code on stackoverflow. Here is my code. What should I do to achieve what I want?

HTML:

<div>
  <table
    mat-table
    [dataSource]="items$ | async"
    class="mat-elevation-z8"
    matSort
  >
    <ng-container matColumnDef="categoryId">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Category Id</th>
      <td mat-cell *matCellDef="let item"></td>
    </ng-container>
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let item"></td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
  </table>
</div>

TS:

 items$: Observable<Item[]>;
  dataSource: MatTableDataSource<Item>;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  displayedColumns: string[] = ['categoryId', 'name'];

  ngAfterViewInit(): void {
    this.items$ = fromFetch(
      'someitems/data/items.json'
    ).pipe(
      switchMap((response) => {
        return response.json();
      })
    );

    this.items$.subscribe(function (result) {
      const grouped = _.groupBy(result, (res) => res.categoryId);
      this.dataSource = result;
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      console.log(grouped);
    });
  }
Via Active questions tagged javascript - Stack Overflow https://ift.tt/brOl3CT

Comments