*ngFor next element

Viewed 3710

I am using Angular Cli. So, my html is:

<div *ngFor="let Item of Items" (click)="add("*next Item should be here*")"></div>

I need to send to function add() not Item but the next element. How I can call;it? And I should stop when the arrow is end in order not to go out of the array

1 Answers

If Items is an array or indexed collection you can use the special index variable and pass that to your function:

<div *ngFor="let item of items; let i = index" (click)="add( i )">

Then inside your add function you would check the index:

add(index: number): void {

    let nextIndex = index + 1;
    if( nextIndex < this.items.length ) {
        // do stuff
    }
    else {
        // error: there is no next-item
    }
}

This is documented here: https://angular.io/api/common/NgForOf

  • 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.
Related