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)">
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With