Angular io (4) *ngFor first and last

46,898

Solution 1

Inside the ngFor you have access to several variables:

  • index: number: The index of the current item in the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.

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>

Solution 2

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 πŸš€

Share:
46,898
Nicholas Fitton
Author by

Nicholas Fitton

Updated on July 09, 2022

Comments

  • Nicholas Fitton
    Nicholas Fitton almost 2 years

    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!

  • Anjana Silva
    Anjana Silva about 4 years
    I am glad I googled. To be honest, I didn't even know these exists, such as last, first etc. Thank you, you are star!