We have to modify the implementation of isAllSelected
, masterToggle
and introduction of new method selectRows
with logic of selecting the current page rows.
So Inside selectRows() method, we have to put the logic of getting the starting index and endIndex till when we have to select the data on current page based on current page Index and size with dataSource length.
Please find the logic with code which I have implemented in my project.
/** Whether the number of selected elements matches the total number of rows. */
isAllSelected() {
const numSelected = this.selection.selected.length;
const page = this.dataSource.paginator.pageSize;
let endIndex: number;
// First check whether data source length is greater than current page index multiply by page size.
// If yes then endIdex will be current page index multiply by page size.
// If not then select the remaining elements in current page only.
if (this.dataSource.data.length > (this.dataSource.paginator.pageIndex + 1) * this.dataSource.paginator.pageSize) {
endIndex = (this.dataSource.paginator.pageIndex + 1) * this.dataSource.paginator.pageSize;
} else {
// tslint:disable-next-line:max-line-length
endIndex = this.dataSource.data.length - (this.dataSource.paginator.pageIndex * this.dataSource.paginator.pageSize);
}
return numSelected === endIndex;
}
/** Selects all rows if they are not all selected; otherwise clear selection. */
masterToggle() {
this.isAllSelected() ?
this.selection.clear() : this.selectRows();
}
selectRows() {
// tslint:disable-next-line:max-line-length
let endIndex: number;
// tslint:disable-next-line:max-line-length
if (this.dataSource.data.length > (this.dataSource.paginator.pageIndex + 1) * this.dataSource.paginator.pageSize) {
endIndex = (this.dataSource.paginator.pageIndex + 1) * this.dataSource.paginator.pageSize;
} else {
// tslint:disable-next-line:max-line-length
endIndex = this.dataSource.data.length;
}
for (let index = (this.dataSource.paginator.pageIndex * this.dataSource.paginator.pageSize); index < endIndex; index++) {
this.selection.select(this.dataSource.data[index]);
}
}