I am trying to tell whether an item in an *ngFor
is the first or last element to style a container. Is there a way to do something like this?
<md-expansion-panel *ngFor="let item of items" *ngClass="{ 'first' : item.isFirst }"> <content></content> </md-expansion-panel>
Thanks for any help offered!
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.
The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.
Inside the ngFor
you have access to several variables:
So:
<md-expansion-panel *ngFor="let item of items; first as isFirst" *ngClass="{ 'first' : isFirst }"> <content></content> </md-expansion-panel>
Documentation at https://angular.io/api/common/NgForOf gives this example:
<li *ngFor="let user of userObservable | async as users; index as i; first as isFirst"> {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> </li>
This how you can do it :
<md-expansion-panel *ngFor="let item of items; let first = first; let last = last" [ngClass]="{ 'first' : first }"> <content></content> </md-expansion-panel>
NgFor provides several exported values that can be aliased to local variables:
index
will be set to the current loop iteration for each template context so it start from 0.
first
will be set to a boolean value indicating whether the item is the first one in the iteration.
last
will be set to a boolean value indicating whether the item is the last one in the iteration.
even
will be set to a boolean value indicating whether this item has an even index.
odd
will be set to a boolean value indicating whether this item has an odd index.
for more information : NgFor-directive 🚀🚀
a complete example
<div *ngFor="let n of items; let itemsCount = count;let idx = index , let isOdd = odd;let first = first ;let last = last;"> {{n}} , {{itemsCount}} , {{idx}} , odd 👉 {{isOdd}} , first 👉 {{first}} , last 👉 {{last}} </div>
demo 🚀
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