Sanchit Kumar
Sanchit Kumar

Reputation: 45

Angular Run *ngFor on particular Indexes Defined in Array

I am using a *ngFor loop but I only want the loop to run on particular indexes defined in an array (i.e. indexArray = [454,640]).

If I try this, and the indexArray has two or more elements, it does not work. But If the array has only one element (i.e. indexArray=[565]) it works.

<div *ngFor="let item of items; index as i">
  <table *ngIf="i == indexArray"> 

Upvotes: 2

Views: 4953

Answers (3)

Piyush Jain
Piyush Jain

Reputation: 1986

create index array like this

public indexArray: array = [454,640];

do like below.

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.indexOf(i)> -1">
    enter code here...
  </table>
</div>

let me know if you have any doubt.

Upvotes: 0

Ivan
Ivan

Reputation: 149

You can do the following:

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.includes(i)">
    enter code here...
  </table>
</div>

Here is a working example

Upvotes: 0

Harshana
Harshana

Reputation: 5476

You can use .indexOf(i) and check whether it is in your indexArray variable.

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.indexOf(i)> -1"> 
  <!-- REST OF THE CODE -->

Upvotes: 5

Related Questions