简体   繁体   中英

How to use the current and also next iteration value inside a ngFor (Angular 4)

This is the loop i have. I need to use the activity object and also the next activity object in a single iteration.Any Thoughts on how to do that ?

 *ngFor="let activity of course.activities; let i = index"

Thanks :)

Assuming that you don't want the last element to be displayed alone

You have to loop only through course.activities.length - 1 . That is exclude the last item, because that gets displayed as the next item of last but one item.

public course = {activities : [1,2,3]};

<div *ngFor = "let a of course.activities.slice(1); let i = index">
  {{course.activities[i]}}-- {{course.activities[i+1]}}
</div>

Loop is required just get the index of an element inside an array

DEMO

I'd rather create chunks of your array, then loop them and just take 0 and 1. For example, to get chunks, you can use (may be different depending on your rxjs version)

export function chunk<T>(arr: T[], chunkSize: number): Observable<T[][]> {
  return Observable.from(arr).pipe(bufferCount(chunkSize)).toArray();
}

then loop in the template

<div *ngFor="let activity of chunkedActivities | async">
    {{ activity[0] }} - {{ activity[1] }}
</div>

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