Maxime Dupré
Maxime Dupré

Reputation: 5737

Create two elements for a single `ngFor` iteration?

I am looping on a collection of models and want to show one element per model. However, for CSS reasons, I must add another element when I reach the forth model (I need to add a Bootstrap clearfix element for the layout to look good).

<div class="jumbotron">
    <ol class="row">
        <li *ngFor="#card of deck; #i = index" class="col-xs-3">
            <h3>{{ card.name }}</h3>
        </li>
    </ol>
</div>

How do I say if (i + 1) % 4 === 0, then add this li plus another <li class="clearfix"></li>?

Upvotes: 16

Views: 8166

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

This can be done with the <ng-container> helper element

  <div class="jumbotron">
    <ol class="row">
        <ng-container *ngFor="let card of deck" let-i="index"> 
          <li class="col-xs-3">
            <h3>{{ card.name }}</h3>
          </li>
          <li *ngIf="(i + 1) % 4 === 0" class="clearfix"></li>
        </ng-container>
    </ol>
  </div>

An alternative approach (used before <ng-container> became available)

This can be done with the long ngFor form with an explicit <template> tag like

  <div class="jumbotron">
    <ol class="row">
        <template ngFor let-card [ngForOf]="deck" let-i="index"> 
          <li class="col-xs-3">
            <h3>{{ card.name }}</h3>
          </li>
          <li *ngIf="(i + 1) % 4 === 0" class="clearfix"></li>
        </template>
    </ol>
  </div>

Plunker example

See also https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

Upvotes: 32

Related Questions