How to capture the selected table row in the Material Design MD table

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

<md-table #table [dataSource]="tableDataSource" (click)="selectRow(row)">
+18
source share
4 answers

I was able to get it to work like this:

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);
  }
+22
source

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

click tr, mat-row, , * matRowDef = "let row;" :

    <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>
Hide result

selectRow () - , .

+12

, click [selectRow (row)] md-row

<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">
+1

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

table-basic-example.html

(click)="test(row)"

table-basic-example.ts

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

.

0

Source: https://habr.com/ru/post/1684988/


All Articles