I have 2 material 2 tables in the same component with sorting. I cannot find a way to assign the MatSort directive to its own table. I\'m only able to use MatSort on the fir
I would recommend to create a common component for table which can be used at multiple places in application. As component will create the separate instance of it, mat table did't conflicts there functionality.
In that case you don't need to repeat the code for 2 tables. Below is Table common component you can implement.
Home.component.ts
export class HomeComponent implements OnInit {
public data1: any[];
public data2: any[];
constructor() {
}
ngOnInit() {
this.data1 = [
{domain: 'Hello1', gNum: 1, gPct: 'table-data1'},
{domain: 'Hello2', gNum: 2, gPct: 'table-data2'},
{domain: 'Hello3', gNum: 3, gPct: 'table-data3'},
{domain: 'Hello4', gNum: 4, gPct: 'table-data4'},
{domain: 'Hello5', gNum: 5, gPct: 'table-data5'},
{domain: 'Hello6', gNum: 6, gPct: 'table-data6'},
{domain: 'Hello7', gNum: 7, gPct: 'table-data7'},
];
this.data2 = [
{domain: 'Hello1', gNum: 1, gPct: 'table-data1'},
{domain: 'Hello2', gNum: 2, gPct: 'table-data2'},
{domain: 'Hello3', gNum: 3, gPct: 'table-data3'},
{domain: 'Hello4', gNum: 4, gPct: 'table-data4'},
{domain: 'Hello5', gNum: 5, gPct: 'table-data5'},
{domain: 'Hello6', gNum: 6, gPct: 'table-data6'},
{domain: 'Hello7', gNum: 7, gPct: 'table-data7'},
]
}
}
Home.component.html
Table.component.ts
@Component({
selector: 'app-table-component',
templateUrl: 'table.component.html',
styleUrls: ['table.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TableComponent implements OnInit, OnChanges {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@Input() data: any[];
public displayedColumns = ['domain', 'gNum', 'gPct'];
public dataSource: MatTableDataSource;
constructor() {
}
public ngOnInit() {
setTimeout(() => {
this.dataSource = new MatTableDataSource(this.data);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
public ngOnChanges(changes: SimpleChanges) {
this.dataSource = new MatTableDataSource(changes.data.currentValue);
}
}
Table.component.html
Domain
{{row.domain}}
G Number
{{row.gNum}}
Global Pct
{{row.gPct}}