简体   繁体   中英

How to manipulate index value in *ngFor?

I am currently using Angular 6 and i ran into a small doubt. How can we manipulate the index variable that we get in the *ngFor according to our needs. For example,

<li *ngFor="let iah of jsonObj; let i = index;">
   <span>{{jsonObj[i].content}}</span>
   <span>{{jsonObj[(i+1)].content}}</span>
</li>

The above snippet will fetch the same object twice and display its content. How is it possible to display i'th object in the first span and (i+1)th object in the second span? Now the way i did it works only for the first iteration. as soon as it moves to the second iteration, repetition will occur. Any ideas about this?

The index variable can't be manipulated in angular. You can place an ngIf* condition before your span div's to change the view. Following is the change in your snippet for reference:

<div *ngFor="let iah of jsonObj; let i = index;">
    <li *ngIf="i%2==0">
        <span>{{jsonObj[i].content}}</span>
        <span>{{jsonObj[(i+1)].content}}</span>
    </li>
</div>

As per my understanding, if you want output like this :

 - test1 test2
 - test2 test3
 - test3 test4
 - test4

then you need to check if your json[i+1] has data or not, because after the last index if you use i+1 the array does not have i+1 value, so it gives you an error.

So you can use it like this in your html:

<li *ngFor="let iah of jsonObj; let i=index;">
    <span> {{ jsonObj[i].content }}</span>
    <span *ngIf="i < jsonObj.length -1"> {{ jsonObj[i+1].content }} </span>
</li>

OR If you want output like this :

- test1 test2
- test3 test4

Than you can use below method:

<ng-template ngFor let-item let-i="index" [ngForOf]="jsonObj">
    <li *ngIf="i%2 == 0">
        <span> {{ jsonObj[i].content }}</span>
        <span *ngIf="i < jsonObj.length -1"> {{ jsonObj[i+1].content }} </span>
    </li>
</ng-template>

Check Stackblitz Live Demo

You won't be able to display it column wise from HTML only.

Modify your array by iterating it. You can do it where you are assigning data in it as:

TS

newJsonObj = [];

for(let i = 0; i<this.jsonObj.length; i++) {
    this.newJsonObj.push({key: this.jsonObj[i].content, value: this.jsonObj[i+1].content})
    i++;
}

HTML

<li *ngFor="let iah of newJsonObj;">
   <span>{{iah.key}} </span>
   <span>{{iah.value}}</span>
</li>

here you can find stackblitz

your index is -1 behind what you really want. This means at the first iteration you print out

index = 0;
jsonObj[0].content
jsonObj[1].content

index= 1;
jsonObj[1].content
jsonObj[2].content

index=2:
jsonObj[2].content
jsonObj[3].content

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM