有一個類似的問題How to pass selected row value of table to button click event - Material design - Angular 6,但是我沒有找到對我的案例有幫助的解決方案。我正在使用 Angular Material 表來顯示我的數(shù)據(jù),我在每行數(shù)據(jù)旁邊都選中了復選框。我想要實現(xiàn)的是用戶應該能夠選擇所需的行,并且在按鈕提交時,所有選定的行都將傳遞到后端進行處理?,F(xiàn)在我的方法是單擊復選框時,它將調(diào)用(click)="onSelectCheckbox(row)"my 中的一個函數(shù)component.ts并將該行附加到數(shù)組中,當用戶取消選擇該行時,它將觸發(fā)相同的函數(shù)并將行對象刪除.filter()。如果我以相對正常的速度單擊復選框,這工作正常,但是當我以更快的速度反復單擊不同的復選框時,邏輯開始出錯。在按鈕提交時,我的控制臺顯示被取消選擇的行仍在數(shù)組中,而被勾選的行不在數(shù)組中。我有這個復選框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); }我確信有更好、更聰明的方法來做到這一點,但我找不到任何有用的資源來做到這一點,任何指導將不勝感激。
Angular Material Table:如何在單擊按鈕時傳遞/提交選定的行?
躍然一笑
2021-11-25 15:47:40