Jakube
Jakube

Reputation: 3574

click() in cell should not trigger click() in row

Given a Angular Material table. Each row shows a name and a link, both in its own cells. I want to call the function rowFunction whenever somebody clicks anywhere on the row, and call the linkFunction whenever somebody clicks the link.

My current solution is the following. The problem is, that clicking on the link will call both the rowFunction and the linkFunction. But I only want to call the linkFunction, not both at the same time.

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let row">{{row.name}}</td>
  </ng-container>

  <ng-container matColumnDef="link">
    <th mat-header-cell *matHeaderCellDef>Link</th>
    <td mat-cell *matCellDef="let row">
      <a (click)="linkFunction(row)">Link</a>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"
     (click)="rowFunction(row)"></tr>
</table>

Link to codesandbox.io: https://codesandbox.io/s/awesome-cookies-qf3bo?file=/src/app/table.component.html

How can I avoid the click to the row, when I click the actual link in the cell?

Upvotes: 3

Views: 1281

Answers (2)

The James
The James

Reputation: 465

I have to handle this as well. I have to support the user being able to select a row as well as to click a link in the row without selecting the row.

I'm handling it like this (the switch statement lists every tag that appears in my rows that I want to treat like a select target) :

public RowClicked(event: any) {
    switch (event.target.nodeName) {
        case "TD":
        case "PROPERTY":
        case "DIV":
        case "SPAN":
        case "P":
            //handle the actual row selection
            break;
    }
}

The tr has a click event like this:

(click)="RowClicked($event)"

Since A isnt in that switch statement, the row select callback isn't called.

Upvotes: 1

spots
spots

Reputation: 2738

You need to pass the click event to your linkFunction and call stopPropagation.

The template:

<td mat-cell *matCellDef="let row">
  <a (click)="linkFunction($event, row)">{{row.link}}</a>
</td>

The function:

linkFunction(evt, row): void {
  console.log("called link function");
  evt.stopPropagation();
}

Here's a stackblitz demonstrating

Upvotes: 3

Related Questions