![](/img/trans.png)
[英]How to pass selected row value of table to button click event - Material design - Angular 6
[英]With Angular Material tables, how to have a click event handler for a table row that ignores one column
我的Angular Material表中有一行要單擊的行。 問題是我在行的最后一列中也有一個圖標,我也想單擊該圖標,但處理方式有所不同。 現在,當我單擊該圖標時,它同時調用了兩個處理程序,但我不希望這樣。 這是我的代碼:
<div class="mat-elevation-z8"> <table mat-table #table [dataSource]="dataSource" matSort aria-label="Publisher"> <!-- LastName Column --> <ng-container matColumnDef="lastName"> <th mat-header-cell *matHeaderCellDef mat-sort-header>Last Name</th> <td mat-cell *matCellDef="let row">{{row.lastName}}</td> </ng-container> <!-- FirstName Column --> <ng-container matColumnDef="firstName"> <th mat-header-cell *matHeaderCellDef mat-sort-header>First Name</th> <td mat-cell *matCellDef="let row">{{row.firstName}}</td> </ng-container> <!-- Actions --> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef></th> <td mat-cell *matCellDef="let row"> <button mat-icon-button (click)="onClickDelete(row.id)"> <mat-icon>delete</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row (click)="onClickPublisher(row.id)" *matRowDef="let row; columns: displayedColumns;"></tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator> </div>
如何做到這一點,以便當我單擊delete
圖標時,它不會調用整行的單擊處理程序?
以下幾件事可能會有所幫助:
將click事件以及ID傳遞到后端代碼中,如下所示:
<button mat-icon-button (click)="onClickDelete($event, row.id)">
<mat-icon>delete</mat-icon>
</button>
然后,您可以在ts中捕獲它。 在圖標上,您可以像這樣嘗試stopPropagation:
onClickDelete(e, id) {
e.stopPropagation();
// do stuff with the id;
}
在該行上,一個選項是檢查目標類列表:
onClickDelete(e, id) {
if (e.target.className.includes('mat-icon-button')) {
return;
}
//Do stuff with id
}
我有類似的問題,我想顯示從表中單擊圖標時彈出的窗口。 這是我的解決方法:
html
<ng-container matColumnDef="delete">
<mat-header-cell *matHeaderCellDef> Delete </mat-header-cell>
<mat-cell *matCellDef="let element">
<button mat-button (click)="showAlert(element)">
<i class="material-icons">delete_forever</i>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selectedRows(row)"></mat-row>
</mat-table>
ts
...
public isClicked = false;
...
showAlert(action) {
this.isClicked = true;
//this open popup
swal({
//popup part
}).then(isConfirm => {
this.isClicked = false;
}, (dismiss) => {
if (dismiss === 'cancel' || dismiss === 'close') {
this.isClicked = false;
}
});
}
然后只需檢查是否單擊了圖標
selectedRows(row){
if(!this.isClicked){
//do what ever you want icon is not clicked
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.