2

My main issue was trying to loop for a certain number of times let's say n, but the ngFor only accepts arrays, like: "#item of [1, 2, ..., n]", so what is the proper way to loop using only the item count (without creating a useless array that has only numbers one to n)?

so I started reading more into the syntax and then i noticed that there are:

  • *ngFor="#item of items;
  • *ngFor="#item in items;

so what is the difference between "in" and "of" and what are there use cases? and does it have anything to do with my original case?

Thanks in advance.

Labib Ismaiel
  • 1,240
  • 2
  • 11
  • 21

3 Answers3

4

There is no

*ngFor="#item in items;

you have to use of. Early versions required in but they changed it to conform to https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...of

It should be

*ngFor="let item of items; ..."

Currently ngFor only iterates over arrays.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

of does refers to each element of items collection which is #item. #item is local variable created for each element rendered by *ngFor.

in was there in Angular 1 version, it isn't supported in Angular2 ngFor syntax.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

for resembling syntax with ES6 angular did this change. In ES6,

for (var v of arr){
   console.log(v); // it will return value (not key like in for...in)
}

Similarly in Angular 2.0 they followed same syntax.

*ngFor="#item of items;

will return values.

in was in angular 1, which was resembled with for(var i in arr). but no more supported in angular 2.0

Anshul
  • 9,312
  • 11
  • 57
  • 74