20

I have a requirement wherein I should be able to capture the selected row [user can click anywhere on the row]. I went through the documentation https://material.angular.io/components/table/overview but I couldn't find a way to capture selected row and its contents. I tried to attach a click event on md-table tag but it didn't work.

<md-table #table [dataSource]="tableDataSource" (click)="selectRow(row)">

4 Answers 4

25

I was able to get it working thusly:

in component.html

  <md-table [dataSource]="dataSource">
    <ng-container mdColumnDef="a">
      <md-header-cell *mdHeaderCellDef> a </md-header-cell>
      <md-cell *mdCellDef="let element"><a routerLink="{{element.number}}"> {{element.a}} </a></md-cell>
    </ng-container>

    <ng-container mdColumnDef="b">
      <md-header-cell *mdHeaderCellDef> b </md-header-cell>
      <md-cell *mdCellDef="let element"> {{element.b}} </md-cell>
    </ng-container>

    <md-header-row *mdHeaderRowDef="['a', 'b']"></md-header-row>
    <md-row *mdRowDef="let row; columns: ['a', 'b']" (click)="selectRow(row)"></md-row>
  </md-table>

and in component.ts

  selectRow(row) {
      console.log(row);
  }
0
15

https://material.angular.io/components/table/overview

You can add your click event to tr element that has mat-row attribute and you have access to row regarding to *matRowDef="let row;" like below :

    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

      <!-- Position Column -->
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>

      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>


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

selectRow(row) is your function that should be written inside your component.

1

I was able to make this work by attaching the click event [selectRow(row)] on md-row instead

<md-table #table [dataSource]="tableDataSource">
   <md-header-row *cdkHeaderRowDef="tableColumns"></md-header-row>
   <md-row *cdkRowDef="let row; columns: tableColumns;" (click)="selectRow(row)"></md-row>
   <ng-container cdkColumnDef="day">
0

In general a click event on the row works

(https://stackblitz.com/edit/angular-nmb2x1?file=app/table-basic-example.html).

Here in the above example

In table-basic-example.html

(click)="test(row)"

In table-basic-example.ts

test(row){
console.log(row)
}

In console it displays the selected table row object.

Not the answer you're looking for? Browse other questions tagged or ask your own question.