9

I am using the Angular2 Material Design data table in my application and it's awesome. I was wondering if there is any way to get the index number or row number? Something like row.index? I noticed in the CDK data table documentation that it mentions that "The directive also exports the same properties as ngFor (index, even, odd, first, last)" but does not have any examples how to get the index.

Any help or guidance is greatly appreciated. Thanks!

Prita Hasjim
  • 343
  • 1
  • 5
  • 15

2 Answers2

24

You can get the row index the same way like *ngFor, add let i = index within the <md-row>

<md-row *cdkRowDef="let row; columns: displayedColumns; let i = index; let isOdd = odd; let isEven = even; let isLast = last" 
         [ngClass]="{'highlight': selectedRowIndex == row.id}"
         (click)="highlight(row, i, isOdd, isEven, isLast)">
</md-row>

ts:

highlight(row, index, oddFlag, evenFlag, lastFlag){
    alert("index:" + index + " odd: " + oddFlag + " even: " + evenFlag + " last: " + lastFlag);
    this.selectedRowIndex = row.id;
}

Plunker demo

Nehal
  • 13,130
  • 4
  • 43
  • 59
12

Thanks @Nehal, that works for that example. I was trying to make unique ID's per entry by using the index so I also found a similar solution where I defined index with cdkCellDef. Below is my solution, where index is i.

<md-cell *cdkCellDef="let row; let i = index;">
  <div id="{{i}}-info">
    index: {{i}}
    info: {{row.info}}
  </div>
</md-cell>
Prita Hasjim
  • 343
  • 1
  • 5
  • 15