Although a similar question has been addressed on Stack Overflow regarding how to pass selected row values of a table to a button click event in Material design using Angular 6, I did not find the solutions provided there helpful for my specific case.
In my project, I am utilizing an Angular Material table to display data with a select checkbox next to each row.
The goal I am aiming for is to allow users to select rows of their choice and upon submitting a button, all the selected rows will be sent to the backend for processing. Currently, I have implemented an approach where clicking on the checkbox triggers a function (click)="onSelectCheckbox(row)"
in my component.ts
, adding the selected row to an array. Deselecting a row invokes the same function and removes the row object using .filter()
.
While this method functions properly when checkboxes are clicked at a normal speed, it encounters issues when checkboxes are rapidly toggled. Upon submission, the console displays deselected rows still present in the array while selected rows are missing.
The checkbox implementation within my mat-table
:
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()" [aria-label]="checkboxLabel()">
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox (click)="onSelectCheckbox(row)" (change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)">
</mat-checkbox>
</td>
</ng-container>
.
.
.
<button class="btn btn-primary" (click)="openSubmitConfirmation()">Submit</button>
The logic behind the onSelectCheckbox(row)
function in my component.ts
, as well as the button to display selected rows in the console for testing:
selectedPayment = new Array<Payment>();
onSelectCheckbox(row: Payment) {
if (this.selectedPayment === undefined || this.selectedPayment.length === 0) {
this.selectedPayment.push(row);
} else if (this.selectedPayment.includes(row)) {
this.selectedPayment = this.selectedPayment.filter(
x => x.payment_reference !== row.payment_reference);
} else {
this.selectedPayment.push(row);
}
}
openSubmitConfirmation() {
console.log(this.selectedPayment);
}
I am certain that there must be a more efficient way of achieving this functionality, but I have yet to come across any valuable resources. Any guidance or suggestions would be greatly appreciated.