Angular 6: Storing value to use in *ngFor

2019-09-05 17:47发布

问题:

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

回答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.



回答2:

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>