Angular 2 index in *ngFor

Resume

Sometimes we need to iterate the array while developing with Angular 2, at that time, we may use *ngFor to iterate every elements in the array.


Introduction

First, codes below illustrate how to use *ngFor.
Suppose we have an array which names fruits and contains [“apple”, “pineapple”, “pear”]. Then we could use the following codes to iterate it.

<div class="father">
    <div class="children" *ngFor="#fruit of fruits">
        {{fruit}}
    </div>
</div>

It means that for each fruit in fruits, we append a div with class children . The final source code should be like this:

<div class="father">
    <div class="children" *ngFor="#fruit of fruits">
        apple
    </div>
    <div class="children" *ngFor="#fruit of fruits">
        pineapple
    </div>
    <div class="children" *ngFor="#fruit of fruits">
        pear
    </div>
</div>

Iterate with index

Since sometimes we need to indicate the number of element while iterating it. We could also add a variable that contains the index of iteration.
Take the same example above, we may construct the code like

<div class="father">
    <div class="children" *ngFor="#fruit of fruits; #i = index">
        No.{{(i + 1) + " " + fruit}}
    </div>
</div>

That will create a page like

<div class="father">
    <div class="children" *ngFor="#fruit of fruits">
        No.1 apple
    </div>
    <div class="children" *ngFor="#fruit of fruits">
        No.2 pineapple
    </div>
    <div class="children" *ngFor="#fruit of fruits">
        No.3 pear
    </div>
</div>

As you can see, we have already printed every element within the list using its index.


Index in function

Also we can use the index in a function, like

HTML file:

<div class="father">
    <div class="children" *ngFor="#fruit of fruits; #i = index" *ngIf="getExistance(i)">
        No.{{(i + 1) + " " + fruit}}
    </div>
</div>

Related TypeScript file:

...
getExistance(i: number){
    return i % 2 == 0;
}
...

We pass i as an argument to the function getExistance(). Then getExistance() determine if the element should appear.

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值