Index number in descending order

1.5k Views Asked by At

My table contains indexing number and when i add a new row its should show me in 2,1,0 i need current value in the top index number 2.As per my code its working 0,1,2. But i need it in 2,1,0.

This is my html file `

<mat-table #table [dataSource]="dataSource"  *ngFor="let field of fieldArray | reverse; let i = index " [attr.data-index]="i" >                 
<ng-container matColumnDef="SrNo">
<mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
<mat-cell *matCellDef="let element" >                 
<div>{{i}}</div>
</mat-cell>
</ng-container>

Here is my pipe code

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
  name: 'reverse',
  pure: false
})
export class ReversePipe implements PipeTransform {

transform (values) {
    return values.reverse();
  }
}
2

There are 2 best solutions below

1
ylerjen On

As it seems you just want the index to be reversed, not the items, instead of using the reverse and displaying the i directly, you could do :

[attr.data-index]="fieldArray.length - i"

and

<div>{{fieldArray.length - i}}</div>

That way you'll get ...,2,1,0 instead of 0,1,2...

0
Abel Valdez On

You can sort directly the array "fieldArray" you dont need to use a pipe.

fieldArray.sort((a, b) => a < b? 1 : 0);