为一次ngFor迭代创建两个元素? [英] Create two elements for a single `ngFor` iteration?

查看:108
本文介绍了为一次ngFor迭代创建两个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在循环查看一组模型,并希望每个模型显示一个元素.但是,出于CSS的原因,我在到达第四个模型时必须添加另一个元素(我需要添加Bootstrap clearfix元素以使布局看起来不错).

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>

怎么说(i + 1) % 4 === 0,然后添加这个li加另一个<li class="clearfix"></li>?

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

推荐答案

这可以通过<ng-container> helper元素

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>


一种替代方法(在<ng-container>可用之前使用)


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

这可以通过带有明显<template>标记的长ngFor形式完成,例如

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>

> 柱塞示例

另请参见 https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

这篇关于为一次ngFor迭代创建两个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆