Trying to add shift click feature to a sorted MatDataTable
using angular and typescript.
When a click event occurs on the table, the selected row is stored.
If a shift click is detected, it should select rows between the last selected and the current row (similar to Windows shift click selection).
Here's the event handling code:
clickHandler(event, row, index) {
console.log('index clicked: ' + index);
if (event.ctrlKey) {
this.selectRows(row, index); // Records this.lastSelected
} else if (event.shiftKey) {
this.selectRowsFill(row, index);
} else {
this.selectElement(row, index); // Also records this.call
}
}
// Function to auto-select rows between this.lastSelected and currently clicked row
selectRowsFill(row, index) {
const indexA = this.lastSelected;
const indexB = index;
if (indexA > indexB) {
this.selectRowsBetween(indexB, indexA); // Descending order
} else {
this.selectRowsBetween(indexA, indexB); // Ascending order
}
}
// Function for actual selection
private selectRowsBetween(start, end) {
let currentIndex = 0;
this.dataSource.data.forEach(row => {
if (currentIndex >= start && currentIndex <= end) {
this.selection.select(row);
}
currentIndex++;
});
}
And in the HTML:
<mat-row *matRowDef="let row; let i = index; columns: cols;" (click)="clickHandler($event, row, i)" [ngClass]="{'inDatabase' : isAdded(row), 'highlight': isSelectedAndAdded(row) || isSelected(row) }">
This code works well if the table is not sorted. Sorting the MatTableDataSource
messes up the selection as it is based on the original order of data. How can I make shift click work on sorted data instead?