Angular 2 - *ngFor : Is there a way to use an alternative end condition?

13,055

Solution 1

*ngFor provides a last value:

  <div *ngFor="let pic of pics; let i = index; let last=last">
    <div *ngIf="last">
      ...
    </div>
  </div>

See also Implementing ngClassEven ngClassOdd for angular 2

Solution 2

I finally solved my issue an ugly but working way... Instead of writing another end condition I did make a loop with an array of length that is calculated by a function. I read my other array (the one with my pics) in that loop.

Angular should really make something for that! Thank you for your help guys!

Example of how to solve it :

<div *ngFor="let galleryIndex of galleryIndexes; let i = index">
    <div *ngIf="whichRowType(galleryIndex) == 3">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
        <small>pics[currentIndex + 1].id</small>
        <small>pics[currentIndex + 2].id</small>
    </div>

    <div *ngIf="whichRowType(galleryIndex) == 2">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
        <small>pics[currentIndex + 1].id</small>
    </div>

    <div *ngIf="whichRowType(galleryIndex) == 1">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
    </div>
</div>
Share:
13,055
glemiere
Author by

glemiere

Why didn't they take the eagles to fly to Mordor?

Updated on June 06, 2022

Comments

  • glemiere
    glemiere almost 2 years

    I come here because after many hours googling, I didn't find a way to use an alternative stop condition for the loops made with the built-in directive : *ngFor.

    Actually any *ngFor finish the loop with this condition : index < array.length. I want to know if there is a way to end a loop with another condition like : i < myVariable.

    If you wonder why I want to do that, it's because I'm working on a picture gallery working this way :

    <div *ngFor="let pic of pics; let i = index">
        <div *ngIf="whichRowType(i) == 3">
            <small>pic[whichIndex(i)].id</small>
            <small>pic[currentIndex + 1].id</small>
            <small>pic[currentIndex + 2].id</small>
        </div>
    
        <div *ngIf="whichRowType(i) == 2">
            <small>pic[whichIndex(i)].id</small>
            <small>pic[currentIndex + 1].id</small>
        </div>
    
        <div *ngIf="whichRowType(i) == 1">
            <small>pic[whichIndex(i)].id</small>
        </div>
    </div>
    

    In this example, I create a row each 3 pics. I have three types of rows : - Display one pic, - Display two pics, - Display three pics.

    The problem is, the index of my first picture on each row is always inferior to the index used to display the row. So if I want to be able to display all my pictures, I have to be able to change my ending condition of my *ngFor.

    Thank you very much for your help!