Angular Mat-table check all after sorting in current page

439 Views Asked by At

I am trying to select all (or check all) in current page on the screen. Let say I am in 1st page (as I have implemented pagination), then I want to select all AFTER I sort a column.

  1. I want to select only those records on the screen (that mean on that page only). For this I already have implemented code and it working before sorting.
masterToggle() {
  this.isAllSelected() ? this.selection.clear() : this.selectRows();
}

selectRows() {
  for (let index = 0; index < this.dataSource.paginator.pageSize; index++) {
    this.selection.select(this.dataSource.data[index]);
    this.selectionAmount = this.selection.selected.length;
  }
}
  1. I want to deselect all (uncheck all) once I click on a header. For this I already implemented code for "name" column and it is working
onHeaderClick() {
  this.selection.clear();
  console.log(this.selection.selected);
}

PROBLEM: When I sort "name" column, and after that I sort, it is selecting rows from another page. As shown in picture, I clicked on select all, but to my eye it selected only 2 records, but actually it selected 5 records. The other 2 are from page no 3, and the last one is from some other page. stackblitz source code

screenshots

1

There are 1 best solutions below

0
On BEST ANSWER

You need to operate on the sortedData list in your selectRows() method:

selectRows() {
    var sortedData = this.dataSource.sortData(this.dataSource.data, this.sort);
    for (let index = this.dataSource.paginator.pageIndex * this.dataSource.paginator.pageSize; index < (this.dataSource.paginator.pageIndex + 1)* this.dataSource.paginator.pageSize; index++) {
        this.selection.select(sortedData[index]);
        this.selectionAmount = this.selection.selected.length;
    }
}