使用 Angular Material tables,如何为忽略一列的 table 行设置单击事件处理程序

With Angular Material tables, how to have a click event handler for a table row that ignores one column

我的 Angular Material table 中有一行我希望可以点击。问题是我在该行的最后一列中也有一个图标,我也希望它是可点击的,但处理方式不同。现在,当我单击该图标时,它会调用两个处理程序,但我不希望这样。这是我的代码:

<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 图标时,它不会为整行调用点击处理程序?

以下几点可能会有所帮助:

像这样将点击事件连同 id 一起传递到后端代码中:

<button mat-icon-button (click)="onClickDelete($event, row.id)">
      <mat-icon>delete</mat-icon>
</button>

那你就可以在ts里抓了。在图标上,您可以像这样尝试停止传播:

onClickDelete(e, id) {
    e.stopPropagation();
   // do stuff with the id;
}

在该行,一个选项是检查目标 class 列表:

onClickDelete(e, id) {
   if (e.target.className.includes('mat-icon-button')) {
       return;
   }
   //Do stuff with id
}

我遇到了类似的问题,我想在 table 中点击图标时显示弹出窗口。这是我的解决方法:

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
    }
}