I am using the MatTable
component from Angular Material to make a dynamic data table.
I need to get the current position of a row. I can easily get the row on which the user clicked but I am unable to know its current position in the list (which depends on sort/filtering/pagination).
Any idea?
To simplify the use case of having a table that can sort, paginate, and filter an array of data, the Angular Material library comes with a MatTableDataSource that has already implemented the logic of determining what rows should be rendered according to the current table state.
Angular Material does not provide a specific component to be used for filtering the MatTable since there is no single common approach to adding a filter UI to table data. A general strategy is to add an input where users can type in a filter string and listen to this input to change what data is offered from the data source to the table.
In the latest versions of Angular Material 11 | 10, we can call renderRows () method after updating the data of a row, if we use an array directly as a source It is shown in the bellow code and there the table is ViewChild of the mat-table.
Sorting in Data Table. Angular material provides matSort directive for sorting purpose and we require to add mat-sort-header to each column header cell that we want to sort and matSort in the mat-table directive.Following is an example to sort table with firstName. Now, we can see the option in our data table to sort based on first name.
in your mat-cell
you can get index like *ngFor
as below
<mat-cell *matCellDef="let element;let i = index;">
{{ i }}
</mat-cell>
Update from Angular 5 use also index as i
<ng-container matColumnDef="rowIndex">
<th mat-header-cell *matHeaderCellDef> Index </th>
<td mat-cell *matCellDef="let element;index as i;"> {{ i }} </td>
</ng-container>
index
: number: The index of the current item in the iterable. first
: boolean: True when the item is the first item in the iterable.last
: boolean: True when the item is the last item in the iterable. even
: boolean: True when the item has an even index in the iterable. odd
: boolean: True when the item has an odd index in the iterable.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With