Search code examples
angularngfor

How can I limit items in ngFor repeat to some number in div and then repeat in Angular?


I have a image gallery and i want x number of image to be in a <div> and then repeat same div for next x number of image. I tried various tricks after searching on google, but all failed. I want to maintain CSS properties of all classes

My code is

<div class="container">
    <div class="myimages">
        <div class="first-column"  *ngFor="let item of projectList | keyvalue">
            <img [src]=' item.value.img' alt="image">
        </div>
    </div>
</div>

Output is like

<div class="container">
    <div class="myimages">
        <div class="first-column">
            <img [src]='1.img' alt="image">
        </div>
        <div class="first-column">
            <img [src]='2.img' alt="image">
        </div>
       <div class="first-column">
            <img [src]='3.img' alt="image">
        </div>
        <div class="first-column">
            <img [src]='4.img' alt="image">
        </div>
    </div>
</div>

Desired output is

<div class="container">
    <div class="myimages">
        <div class="first-column">
            <img [src]='1.img' alt="image">
            <img [src]='2.img' alt="image">
            <img [src]='3.img' alt="image">
            <img [src]='4.img' alt="image">
        </div>
        
        <div class="first-column">
            <img [src]='5.img' alt="image">
            <img [src]='6.img' alt="image">
            <img [src]='7.img' alt="image">
            <img [src]='8.img' alt="image">
        </div>
    </div>
</div>

Solution

  • Make use of index in combination with modulus operator in your loop:

    <div class="container">
        <div class="myimages">
            <ng-container *ngFor="let item of projectList | keyvalue" let-i="index">
                <div class="first-column" *ngIf="i % 4 === 0">
                    <img [src]="projectList[i].value.img" alt="image">
                    <img [src]="projectList[i + 1].value.img" alt="image">
                    <img [src]="projectList[i + 2].value.img" alt="image">
                    <img [src]="projectList[i + 3].value.img" alt="image">
                </div>
            </ng-container>
        </div>
    </div>