After a long search, I finally found the resolution to your issue, as well as the full resolution and link to where I found certain pieces. Hopefully this works for you, as it is finally working for me.
Edit: This answer worked for me on Angular 4, so I can’t speak to the later versions. Based on a comment from someone below, it appears another answer solves this problem for later versions of Angular.
import { Component, AfterViewInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MatSort, MatTableDataSource } from '@angular/material';
@Component({
templateUrl: './my-tables.component.html'
})
export class CopyInstructionsComponent implements AfterViewInit {
public myFirstTableData: MatTableDataSource<MyTableModel>;
public mySecondTableData: MatTableDataSource<MyTableModel>;
@ViewChild('firstTableSort') public firstTableSort: MatSort;
@ViewChild('secondTableSort') public secondTableSort: MatSort;
constructor(private cdRef: ChangeDetectorRef) {
// ...the rest of your code here to build the data structures.
}
ngAfterViewInit() {
this.myFirstTableData.sort = this.firstTableSort;
this.mySecondTableData.sort = this.secondTableSort;
// See => https://stackoverflow.com/questions/39787038/how-to-manage-angular2-expression-has-changed-after-it-was-checked-exception-w
this.cdRef.detectChanges()
}
}
<mat-table
#firstTable
#firstTableSort="matSort"
[dataSource]="myFirstTableData"
matSort
>
<ng-container matColumnDef="column1">
<mat-header-cell *matHeaderCellDef mat-sort-header>Column 1</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.column1 }}</mat-cell>
</ng-container>
</mat-table>
<mat-table
#secondTable
#secondTableSort="matSort"
[dataSource]="mySecondTableData"
matSort
>
<ng-container matColumnDef="column1">
<mat-header-cell *matHeaderCellDef mat-sort-header>Column 1</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.column1 }}</mat-cell>
</ng-container>
</mat-table>