Hamza Haddad
Hamza Haddad

Reputation: 1556

Angular ngfor set empty grid if condition matches

I'm looping an array which it's length could change on a three column row ( on desktop view.

html

<div  class="row" >
  <div *ngFor="let indicator of fiveElements; let index = index"
    class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 pb-4 pl-3 pr-3 indicatorContainer">
    <div>{{index}}</div>
  </div>
</div>

ts

export class AppComponent  {
fiveElements = [1,2,3,4,5]

}

I would that when the array length is equal to 4 the third column is empty

Here's a schema to explain

empty grid

Here's a demo

Upvotes: 0

Views: 802

Answers (1)

Geggi632
Geggi632

Reputation: 564

If I understood your question right - I would do it like this:

<div class="row">
    <div *ngFor="let indicator of fourElements; let index = index" class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 pb-4 pl-3 pr-3 indicatorContainer">
        <div *ngIf="index !== 3 && fourElements.length === 4">{{index}}</div>
        <!--- third column should get empty -->
    </div>
</div>

Thanks for clarification - now I know what you want :) You can achieve this by using the longhand syntax for ngFor:

<div class="row">
        <ng-template ngFor let-indicator [ngForOf]="fourElements" let-index="index">
            <div *ngIf="index === 2 && fourElements.length === 4" class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 pb-4 pl-3 pr-3 indicatorContainer">
            </div>
            <div class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 pb-4 pl-3 pr-3 indicatorContainer">
                <div>{{index+1}}</div>
            </div>
        </ng-template>
    </div>

Upvotes: 2

Related Questions