Search code examples
angular-materialangular6angular-material-table

How do I use matSort to sort the columns in mat-table?


I am trying to implement sorting in mat-table but it does not work at all. I am not getting any errors.

Here is my code.

This is my component.ts file

export class TerminalsComponent implements OnInit {

      cols: string[] = ['select', 'serialKey', 'cameras', 'status', 'activeSince', 'created', 'updated', 'addCamera', 'more'];

      success: boolean;
      message: string;

      dataSource;

      expandedElement: any;

      initialSelection = [];
      allowMultiSelect = true;
      selection = new SelectionModel<any>(this.allowMultiSelect, this.initialSelection);

      @ViewChild(MatSort) sort: MatSort;
      constructor(public cs: Service) {

        this.getTerminals();
      }

      masterToggle() {
        this.isAllSelected() ?
          this.selection.clear()
          : this.dataSource.data.forEach(row => this.selection.select(row));
      }

      isAllSelected() {
        const numSelected = this.selection.selected.length;
        const numRows = this.dataSource.data.length;
        return numSelected === numRows;
      }

      // Expandable Row
      isExpansionDetailRow(i: number, row: Object) {
        return row.hasOwnProperty('detailRow');
      }

      getTerminals() {
        this.cs.getTerminals().subscribe(
          (response) => {
            this.success = response.success;
            this.message = response.msg;
            if (response.success) {
              this.dataSource = new MatTableDataSource(response.data);

              this.dataSource.sort  = this.sort;
              console.log(this.dataSource);

            }

            setTimeout(function () {
              this.message = "";
            }.bind(this), 2000);
          },
          (error) => {
            this.success = error.success;
            this.message = "Cannot get terminals" + error.message;
          }
        );
      }

      ngOnInit() { }

}

Terminals, the dataSource for the mat-table, is array of nested objects. serialKey is a string.

Here is the code snippet of my component.html file. I have added mat-sort-header to serialKey column.

  <mat-table class="list-table" [dataSource]="dataSource" matSort matSortActive="serialKey" matSortDirection="asc">

    <ng-container matColumnDef="serialKey">
      <mat-header-cell mat-sort-header class="align-center" *matHeaderCellDef>Serial Key</mat-header-cell>
      <mat-cell class="align-center" *matCellDef="let element">{{element.serial_num}}
      </mat-cell>
    </ng-container>

    </mat-row>

  </mat-table>

It will be great if someone could tell me what I am missing here, to sort the table.


Solution

  • I had to wrap mine in a setTimeout, if this does not work in your case please let me know and I will delete this answer.

    setTimeout(() = > this.dataSource.sort  = this.sort);