Reputation: 15524
In my angular 6 app I have a material table, which has a checkbox column. When the checkbox is clicked, I need to capture the table row, to which is belongs, so I can update the underlying database record. How do I get a hold of that entire row? Here is the html for the table:
<div class="example-container mat-elevation-z8">
<mat-table #table [dataSource]="dataSource">
<ng-container matColumnDef="checked">
<mat-header-cell *matHeaderCellDef>Check</mat-header-cell>
<mat-cell *matCellDef="let element">
<mat-checkbox [(ngModel)]="element.checked" (change)=updateCheckedList($event)></mat-checkbox>
</mat-cell>
</ng-container>
<ng-container matColumnDef="position">
<mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="weight">
<mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{hovered: row.hovered, highlighted: row.highlighted}" (click)="row.highlighted = !row.highlighted" (mouseover)="row.hovered = true" (mouseout)="row.hovered = false"></mat-row>
</mat-table>
</div>
Here is the updateCheckedList($event) handler in my app.component.ts:
updateCheckedList(eventTaget) {
console.log('event target: ' + eventTaget.target);
}
The eventTaget.target comes off as undefined, where my goal os to get ahold of the entire row, to which that checkbox cell belongs
What is the proper technique for capturing the whole table row?
Upvotes: 3
Views: 6917
Reputation: 1681
For that you need to pass the index of your checkbox also using *matCellDef="let element; let i=index"
your column will look like this
<ng-container matColumnDef="checked">
<mat-header-cell *matHeaderCellDef>Check</mat-header-cell>
<mat-cell *matCellDef="let element; let i=index">
<mat-checkbox (change)=updateCheckedList(element)></mat-checkbox>
</mat-cell>
</ng-container>
now you can get the entire object in updateCheckedList method using index
updateCheckedList(element)
{
console.log(element);
}
Upvotes: 4