I'm trying to get the index of row in table, in html, which has been implemented using angular material v5.2. Is there any method available to get the index?
The code for reference:
<div class="example-container mat-elevation-z8">
<div class="example-header">
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
</div>
<mat-table #table [dataSource]="dataSource">
<!-- Position Column -->
<ng-container matColumnDef="position">
<mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<button (click)="doSomething()"> Do something</button>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
The method doSomething is what needs index.
Any help would be greatly appreciated.
Using indexOf is an enormous waste of resources. The right way is initializing a variable with index's value, like this:
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Num. </th>
<td mat-cell *matCellDef="let element; let i = index">{{i + 1}}</td>
</ng-container>
https://material.angular.io/components/table/examples
UPDATE:
If you are using pagination the index can be calculated this way:
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Num. </th>
<td mat-cell *matCellDef="let i = index">
{{this.paginator.pageIndex == 0 ? i + 1 : 1 + i + this.paginator.pageIndex * this.paginator.pageSize}}
</td>
</ng-container>