1
votes

I am following the basic example on angular material website. It shows the table with correct data but sorting does not work.

Here is the stackblitz: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts

TS File

export class TableSortingExample implements OnInit, AfterViewInit {
  ELEMENT_DATA: any;
  dataSource: MatTableDataSource<any>;
  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.ELEMENT_DATA = {
      customerHeader: ["ID", "Name", "Address"],
      customerDataRows: [
        ["1", "Mark", "10"],
        ["2", "John", "110"],
        ["3", "John", "110"]
      ]
    };

    this.dataSource = new MatTableDataSource(
      this.ELEMENT_DATA.customerDataRows
    );
  }
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

HTML File

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  <ng-container
    *ngFor="let custColumn of ELEMENT_DATA.customerHeader; let colIndex = index"
    matColumnDef="{{ custColumn }}"
  >
    <mat-header-cell *matHeaderCellDef mat-sort-header
      >{{ custColumn }}</mat-header-cell
    >
    <mat-cell *matCellDef="let customerRow">
      {{customerRow[colIndex]}}
    </mat-cell>
  </ng-container>

  <mat-header-row
    *matHeaderRowDef="ELEMENT_DATA.customerHeader; "
  ></mat-header-row>
  <mat-row *matRowDef="let row; columns: ELEMENT_DATA.customerHeader"></mat-row>
</table>
1
Did you already view the example code on the angular material documentation site?Igor
@Igor yeah, this is little different if you look at my stackblitz. I can add html here as wellLearn AspNet

1 Answers

0
votes

Try using key/value objects instead of simple arrays with info that depends on their position. For example, a quick change to your code transforming your arrays of customer data in objects make your code sort the table.

In table-sorting-example.ts, change from:

      customerDataRows: [
        ["1", "Mark", "10"],
        ["2", "John", "110"],
        ["3", "John", "110"]
      ]

to:

customerDataRows: [
   { ID: "1", Name: "Mark", Address: "10" },
   { ID: "2", Name: "John", Address: "110" },
   { ID: "3", Name: "John", Address: "110" }
]

And in table-sorting-example.html from {{customerRow[colIndex]}} to {{customerRow[custColumn]}}

P.S.: I like all keys in lowercase, but only wanted to change the code quickly to show you the result.

See a fork of your project with the changes.