I have a collection of items, where each item have a rank
attribute, which is a number. I wan to loop over this number, here is what I've tried:
<div class="col-md-3 col-sm-4 item-container" *ngFor="let item of items"> <div class="item"> <p class="rank"> <img src="" class="img-responsive" *ngFor="let rank of item.rank"/> </p> </div> </div>
typescript:
export class MonthpicksComponent{ items: Item[] = []; //... } export class Item{ id: number; name: string; img: string; desc: string; rank: number; voters: number; }
but unlucky the first loop shows only one result and the second loop showed nothing.
The for–in loop is for looping over object properties. The for–of loop is for looping over the values in an array. for–of is not just for arrays. It also works on most array-like objects including the new Set and Map types which we will cover in the next lecture.
Approach 1: Using the for loop: The HTML elements can be iterated by using the regular JavaScript for loop. The number of elements to be iterated can be found using the length property. The for loop has three parts, initialization, condition expression, and increment/decrement expression.
*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.
Maybe the simplest solution without any TS code:
<div *ngFor="let item of [].constructor(10); let i = index"> {{i}} </div>
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