Reputation: 815
I have a page with 2 mat-tables populated from 2 data sources. The sorting isn't working for me. Please advise. Here is the stackblitz link
TS File
export class TableSortingExample implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
displayedColumns2: string[] = ['position2', 'name2', 'weight2'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
dataSource2 = new MatTableDataSource(ELEMENT_DATA2);
@ViewChildren(MatSort)
sort = new QueryList<MatSort>();
ngOnInit() {
this.dataSource.sort = this.sort.toArray()[0];
this.dataSource2.sort = this.sort.toArray()[1];
}
}
I couldn't put the html file here, stackoverflow said too much code in question. Please go over to the stackblitz to see the html.
Upvotes: 1
Views: 3818
Reputation: 10707
I think the problem is related to column names and keys of an object that you are using for iteration:
For example:
DataSource
for the second table
const ELEMENT_DATA2: any[] = [
{ position: 11, name: 'Hydrogen', weight: 1.0079 },
{ position: 12, name: 'Helium', weight: 4.0026 },
{ position: 13, name: 'Lithium', weight: 6.941 },
{ position: 14, name: 'Beryllium', weight: 9.0122 }
];
Column names for the second table is:
displayedColumns2: string[] = ['position2', 'name2', 'weight2'];
which actually mismatch from above object key, so just change the JSON Object which matches the keys
same as displayedColumns2
so the sort function will know the columns names on which it has to sort.
Like:
const ELEMENT_DATA2: any[] = [
{ position2: 11, name2: 'Hydrogen', weight2: 1.0079 },
{ position2: 12, name2: 'Helium', weight2: 4.0026 },
{ position2: 13, name2: 'Lithium', weight2: 6.941 },
{ position2: 14, name2: 'Beryllium', weight2: 9.0122 }
];
Upvotes: 3
Reputation: 4143
Here is how it should work for the first table and second at once. But you still have to make small changes to make sorting tables works separated for each table alone.
I have tested it on your code on Stackblitz, and it works.
I commented out the stuff you have to change/remove. And don't forget to import ViewChild
from @angular/core
I'am not sure if you do need it also in ngAfterViewInit
.
Hope it helps you and put you in the right direction.
export class TableSortingExample implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
displayedColumns2: string[] = ['position2', 'name2', 'weight2'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
dataSource2 = new MatTableDataSource(ELEMENT_DATA2);
// @ViewChildren(MatSort)
// sort = new QueryList<MatSort>();
@ViewChild(MatSort) sort: MatSort;
numberOfMatSort = 0;
ngOnInit() {
// this.dataSource.sort = this.sort.toArray()[0];
// this.dataSource2.sort = this.sort.toArray()[1];
this.dataSource.sort = this.sort;
}
ngAfterViewInit() {
console.log(this.sort);
// this.sort.forEach(m => console.log(m));
// setTimeout(() => this.numberOfMatSort = this.sort.length, 0);
this.dataSource.sort = this.sort;
}
}
Upvotes: 0