简体   繁体   中英

Sorting is not working on Material Table in Angular

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>

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]}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM