I'm using *ngFor
to iterate some data like this:
<div *ngFor="let d of [1, 2, 3]"> {{d}} </div>
Everything is fine and I got the result as expected:
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
Then, I wondered if I use a function instead of {{d}}
, so I wrote a function:
protected logAndReturn(item) {
console.log(item);
return item;
}
and I used it:
<div *ngFor="let d of [1, 2, 3]"> {{logAndReturn(d)}} </div>
I got the same rendered HTML result as the first code, but console output wasn't my expected output. Console output:
1
2
3
1
2
3
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
1
2
3
1
2
3
The added function was called 12 times now (4 time for each item)
Here is the code that you can test it yourself: jsfiddle
Is my code wrong? Is there any solution to prevent these extra calls? Why did this happen and can anybody explain it a little?