有一个类似的问题How to pass selected row value of table to button click event - Material design - Angular 6,但是我没有找到对我的案例有帮助的解决方案。
我正在使用 Angular Material 表来显示我的数据,我在每行数据旁边都选中了复选框。
我想要实现的是用户应该能够选择所需的行,并且在按钮提交时,所有选定的行都将传递到后端进行处理。现在我的方法是单击复选框时,它将调用(click)="onSelectCheckbox(row)"my 中的一个函数component.ts并将该行附加到数组中,当用户取消选择该行时,它将触发相同的函数并将行对象删除.filter()。
如果我以相对正常的速度单击复选框,这工作正常,但是当我以更快的速度反复单击不同的复选框时,逻辑开始出错。在按钮提交时,我的控制台显示被取消选择的行仍在数组中,而被勾选的行不在数组中。
我有这个复选框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>
以及onSelectCheckbox(row)我component.ts和我的按钮中的逻辑来测试并在我的控制台中显示选定的行:
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);
}
我确信有更好、更聪明的方法来做到这一点,但我找不到任何有用的资源来做到这一点,任何指导将不胜感激。
吃鸡游戏
相关分类