Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 772
B Snow Avatar asked Apr 25 '17 23:04

B Snow


People also ask

What is the correct way to apply filter in Angular?

Filters can be added to expressions by using the pipe character | , followed by a filter.

How do I filter values from an array in TypeScript?

To filter an array of objects in TypeScript: Call the filter() method on the array. Check if the property on the current object meets the condition. The returned array will only contain objects that satisfy the condition.

Can we apply pipe in ngFor?

Basically, you write a pipe which you can then use in the *ngFor directive. Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results. Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.


1 Answers

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

refer plunker.

like image 136
Pengyy Avatar answered Sep 28 '22 12:09

Pengyy