Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate two arrays in *ngFor-- IONIC2/Angular2

I have stored values in two arrays to iterate in a single ion-list . Billerstatusstate and Billerstatusnamelst are the two arrays.

I have tried the following to iterate

<ion-list ion-item *ngFor="let stat of Billerstatusstate;let bil of Billerstatusnamelst "  >

  {{bil}} <button round>{{stat}}</button>

</ion-list>

and

<ion-list ion-item *ngFor="let stat of Billerstatusstate" *ngFor="let bil of Billerstatusnamelst "  >

  {{bil}} <button round>{{stat}}</button>

</ion-list>

Its taking first iterated value for both local variable.

Is there something am i missing ??

is there anyother way to store both values in single array and split it in View side using ngFor..

like image 940
Kartiikeya Avatar asked Jun 29 '16 13:06

Kartiikeya


3 Answers

I could create a pipe to "merge" your two arrays into a single one and then you can iterate over this new array.

Here is a sample:

@Pipe({
  name: 'merge'
})
export class MergePipe {
  transform(arr1, arr2) {
    var arr = [];
    arr1.forEach((elt, i) => {
      arr.push({ state: elt, name: arr2[i] });
    });
  }
}

And use it this way:

<ion-list ion-item *ngFor="let elt of Billerstatusstate | merge:Billerstatusnamelst"  >
  {{elt.name}} <button round>{{elt.state}}</button>
</ion-list>    
like image 182
Thierry Templier Avatar answered Oct 07 '22 16:10

Thierry Templier


You can leverage the index of the ngFor directive to achieve this.

<ion-list ion-item *ngFor="let stat of Billerstatusstate; let i=index">

  {{Billerstatusnamelst[i]}} <button round>{{stat}}</button>

</ion-list>
like image 33
rinukkusu Avatar answered Oct 07 '22 17:10

rinukkusu


Why instead of doing this

<ion-list ion-item *ngFor="let stat of Billerstatusstate;let bil of Billerstatusnamelst "  >

  {{bil}} <button round>{{stat}}</button>

</ion-list>

don't you create a single array in your code:

// I'm assuming they both have the same size
for (var _i = 0; _i < Billerstatusstate.length; _i++) {
    this.singleArray.push({
                         stat: this.Billerstatusstate[_i],
                         bil: this.Billerstatusnamelst[_i] 
                        });
}

And then in your page:

<ion-list ion-item *ngFor="let item of singleArray;"  >

  {{item.bil}} <button round>{{item.stat}}</button>

</ion-list>
like image 44
sebaferreras Avatar answered Oct 07 '22 16:10

sebaferreras