Angular 6: Storing value to use in *ngFor
Asked Answered
D

2

0

In the loop body in the code below:


<ul>
   <li *ngFor="let article of articles; index as i">
       <a>{{ articles[i].title }} -- {{i}}</a>
       <p>{{ articles[i].body }}</p>
       <!-- i++ -->  
       <p>{{ i }}</p>
   </li>
</ul>

Is there anyway to store the value of i++ at that position, then print out new value of i?

Then, i's value is updated with the new value and used in the next loop. I would like to loop 2 elements at a time, not just one.

It's just like what we can do in Java as below:


for (int i = 0; i < 10; i++) {
    System.out.println(i);
    i++;
    System.out.println(i);
}

1st loop:

0

1

2nd loop:

2

3

and so on..


I found the solution, which is in this link: Looping through list two at a time using *ngFor

Solution: split array into a 2-dimensional array, it's easy to loop using ngFor

Douala answered 11/10, 2018 at 8:55 Comment(9)
Why not just render <p>{{ i+1 }}</p>Sheila
template should never change values unless it is done in event binding e.g. (click)Aleciaaleck
The reason why <p>{{ i+1 }}</p> is not usable is that I would like to process 2 element at a time. Not just oneDetermined
Then please edit your question, and write exact result you want to achieve. All we can see is that you want to render 'i' with +1.Sheila
you can't do it like this. complex way to do.If you relly want i can helpLowerclassman
It's not really good practice to change the iteration values inside a loop. It's better to have for example an *ngIf="i % 2 === 0" before the code you want to display (if you want to display all even indexes).Unalloyed
Ok, next time you should actually try to search for the answer before asking the question. #43234917Sheila
@Sheila excellent post!! thanks very much!!Determined
check this question Angular 2: How to write a for loop, not a foreach loopDerma
S
1

If question stays relevant, for those who are seeking the answer, I would recommend you to refer to this post: Looping through list two at a time using *ngFor

The post is not mine, but it shows a simple solution using the pipeline.

Sheila answered 11/10, 2018 at 9:25 Comment(0)
S
1

Use this function to transform your data to the type of structure you want to access it.

someData = [1,2,3,4,5,6];

transformData(data) {
    let temp = []
    for(let i = 0; i < data.length; i++) {
      let temp2 = [];
      temp2.push(this.data[i]);
      i++;
      temp2.push(this.data[i])
      temp.push(temp2);
    }
    return temp;
  }

then access it in your html like this

<p *ngFor="let data of transformData(someData)">
{{data[0]}}, {{data[1]}}
</p>
Sauls answered 11/10, 2018 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.