<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>
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.
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.
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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With