Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 414
Maxime Dupré Avatar asked Apr 02 '16 16:04

Maxime Dupré


People also ask

Can you have 2 ngFor?

You can't use multiple *ngFor s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template element which then holds the directive itself, you can read more about it here: https://angular.io/guide/structural- ...

What does * mean in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.

How do you use ngFor in a tag?

We loop over each person in the people array and print out the persons name. The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.


1 Answers

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

like image 96
Günter Zöchbauer Avatar answered Sep 17 '22 15:09

Günter Zöchbauer