moreirapontocom
moreirapontocom

Reputation: 458

Reorder *ngFor list and indexes

I'm facing this issue on my Angular project. I have a simple table with a couple of columns (I just pasted only two columns o make easier to explain).

<table>
  <tr>
    <th>#</th>
    <th (click)="orderBy()">Name</th>
  </tr>
  <tr *ngFor="let item of items; let i = index">
    <td>{{ i }}</td>
    <td>{{ item.name }}</td>
  </tr>
</table>

The code above will print a table with a count in the first column. Like this

+---+------+
| # | Name | -> onClick() event is here
+---+------+
| 1 | AAAA |
+---+------+
| 2 | BBBB |
+---+------+
| 3 | CCCC |
+---+------+

To reorder the list I put a "orderBy()" method on each column. The method is

orderBy = () => this.items.sort((a, b) => (a.name > b.name) ? 1 : -1)

When I click on column header, the columns is reordered correctly

        +----------- This column is sorted correctly
        |
+---+------+
| # | Name |
+---+------+
| 1 | CCCC |
+---+------+
| 2 | BBBB |
+---+------+
| 3 | AAAA |
+---+------+
  |
  +------------ This column keeps the index counter

My question is: How to reorder the index (first column)?

The correct result must be this:

+---+------+
| # | Name |
+---+------+
| 3 | AAAA |
+---+------+
| 2 | BBBB |
+---+------+
| 1 | CCCC |
+---+------+
  |
  +------------- This column must "follow" the other column new order

Thank you in advance.

Upvotes: 0

Views: 819

Answers (1)

Barremian
Barremian

Reputation: 31115

Instead of using index in the for rendering, you could introduce a new id property for each object of the array. Now each id would be bound to the object.

Try the following

Component (Illustration)

 this.items.forEach((item, index) => item.id = index + 1);

Template

<table>
  <tr>
    <th>#</th>
    <th (click)="orderBy()">Name</th>
  </tr>
  <tr *ngFor="let item of items">
    <td>{{ item?.id }}</td>
    <td>{{ item?.name }}</td>
  </tr>
</table>

Upvotes: 3

Related Questions