How can I set i=index of array before I filter it in Angular 2?
Asked Answered
E

2

5

I am currently having trouble when paginating a list of clients in Angular 2. Here is a snippet of my code:

<tr *ngFor="let client of eClients | filter:term | paginate: { itemsPerPage: 20, currentPage: p}; let i = index" (click)="toggleClient(i)">
   <td>
    <checkbox [(ngModel)]="eClients[i].selected">
     {{client.name}}
    <checkbox>
   </td>
</tr>

The problem is the index is not corresponding to the actual position in the array. For example, if I go to page 2 and click on client #2 in the list I should get an index of 22, however I am getting 2. It seems that the index only spans from 0-19 as I move from page to page. It is filtering the data first and then setting an index. How can I set "i=index" before any of the filters or pagination take place?

P.s. "checkbox" is my own module and "term" is my own pipe filter.

Please help. Thank You

Earlearla answered 25/4, 2017 at 23:26 Comment(2)
Maybe it works: {{ ((p - 1) * itemsPerPage) + i }} or.. you can use .map() and create a property called index and store index on each object itself. So, in template you can access eClients[client.index].Bibi
Thanks for your help. Unfortunately, neither method worked. First method I am unable to access itemsPerPage or p in the template or when I am making calls to (click)=toggleClient(). Second method worked well for the template but also getting error for the click function when I do (click)=toggleClient(eClients[client.index]). Cannot use client in the functionEarlearla
I
7

The variable index of *NgFor is for current result. For your situation, you can get the original index by eClients .indexOf(client).

refer plunker.

Infect answered 26/4, 2017 at 2:6 Comment(1)
Wow, thank you for taking the time to help me with this I really appreciate it! This worked perfectly. I was starting to get ready to change my whole code around.Earlearla
C
0

add fromGroupName for the formArray

[formGroupName] = "getFormGroupIndex(i)"

for this function compute index:

getFormGroupIndex(index: number): number {
   return index + (this.TableCurPage - 1) * this.ItemPerpage;}
Cattan answered 29/9, 2018 at 0:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.