Create two elements for a single `ngFor` iteration

2019-02-14 05:43发布

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>?

1条回答
Emotional °昔
2楼-- · 2019-02-14 06:15

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

查看更多
登录 后发表回答