32
<div *ngFor="let item of list">
  <div *ngIf="item == previousItem"></div>
  <div *ngIf="item == firstItem"></div>
</div>

How can we make this type of thing work? That is, how can we access other items in the list either (1) in relation to the current index or (2) by absolute index?

EDIT: What if the list was instead an Observable?

<div *ngFor="let item of observable">
  <div *ngIf="item == previousItem"></div>
  <div *ngIf="item == firstItem"></div>
</div>
Ray Zhang
  • 1,411
  • 4
  • 18
  • 36

2 Answers2

42

You can take advantage of the index property of *ngFor

<div *ngFor="let item of list; let i = index;">
  <div *ngIf="item == list[i-1]"></div>
  <div *ngIf="item == list[0]"></div>
</div>

You can find more info on *ngFor local variables in the docs: https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

eko
  • 39,722
  • 10
  • 72
  • 98
26

Based on the accepted answer, I found this useful to know. If you are using *ngFor with an async call you can do the following:

<div *ngFor="let item of list | async as items; let i = index;">
  <div *ngIf="items.length > 0 && item === items[i-1]"></div>
  <div *ngIf="item === items[0]"></div>
</div>
Jacob Aldridge
  • 286
  • 3
  • 7