Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...