Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access previous/later elements within an ngFor loop?

Tags:

angular

<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> 
like image 303
Ray Zhang Avatar asked May 18 '17 20:05

Ray Zhang


People also ask

How do I get ngFor loop unique records?

Create a list of unique items in your controller, and loop over that. *ngFor can't help you here. You can create a pipe that filters duplicates, or you can use a list in *ngFor that already has the duplicates filtered.

Is last in ngFor?

Note, index is not only the value that we get using ngFor directive. But, we can also get the first (“first“) and last (“last“) element by assigning it's value to a variable as well. And the value of the variable will be boolean based on whether the current element is first or last.

What does * mean in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.


2 Answers

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

like image 179
eko Avatar answered Sep 20 '22 02:09

eko


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> 
like image 23
Jacob Aldridge Avatar answered Sep 23 '22 02:09

Jacob Aldridge