Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture selected table row in a Material Design md-table

Tags:

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)">
like image 776
nsk Avatar asked Sep 03 '17 17:09

nsk


Video Answer


2 Answers

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);
  }
like image 77
Joshua Craven Avatar answered Sep 19 '22 07:09

Joshua Craven


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.

like image 45
Jalaleddin Hosseini Avatar answered Sep 18 '22 07:09

Jalaleddin Hosseini