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