Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get index of row in angular material table v5

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.

like image 732
ShivangiBilora Avatar asked May 11 '18 12:05

ShivangiBilora


People also ask

What is MatColumnDef?

MatColumnDef extends CdkColumnDefDefines a set of cells available for a table column.


1 Answers

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> 
like image 146
zgluis Avatar answered Sep 19 '22 11:09

zgluis