Reputation: 1164
What is the difference between : *ngFor='let n in list'
and *ngFor='let n of list'
I just recently stumbled upon it. Searched through some old questions couldn't find any satisfactory answer.
Upvotes: 2
Views: 289
Reputation: 11162
The syntax
*ngFor='let n in list'
is not valid Angular syntax.
To prove it, creating a new angular project with a minimal app.component.ts
file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let n in list">{{n}}</li>
</ul>
`
})
export class AppComponent {
public list = [1,2,3,4,5];
}
Results in the error
compiler.js:486 Uncaught Error: Template parse errors:
Can't bind to 'ngForIn' since it isn't a known property of 'li'. ("
<ul>
<li [ERROR ->]*ngFor="let n in list">{{n}}</li>
</ul>
"): ng:///AppModule/AppComponent.html@2:8
Property binding ngForIn not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
<ul>
[ERROR ->]<li *ngFor="let n in list">{{n}}</li>
</ul>
You can however create a custom directive to handle this (as mentioned in this article).
As for the difference between of and in the article mentions the following:
NgFor is Angular’s equivalent of the for…of statement in JavaScript, looping over an iterable object and taking each of its values one by one. There’s also the for…in statement which instead iterates over the enumerable properties of an object, but there’s no Angular equivalent to that, so let’s make one.
Upvotes: 2
Reputation: 1425
in JavaScript
for…in statement which instead iterates over the enumerable properties of an object
and
for…of statement looping over an iterable object taking each of its values one by one
Upvotes: 1