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>
?
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- ...
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With