0

Why *ngFor repeat for (array count) x 4 times ?

I have created simple Angular2 project using Angular-cli. I am using Angular4.

AppComponent (app.component.ts)

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    values = [1, 2, 3, 4, 5];

    protected square(v) {
        const retVal = v * v;
        console.log(retVal, new Date().getMilliseconds());
        return retVal;
    }
}

app.component.html

<div *ngFor="let v of values">
    <span>{{square(v)}}</span>
</div>

Result (rendered HTML)

enter image description here

Question ??

In HTML it is producing only 5 elements but when you look at console it is printing 20 times.

What I believe it should be only call square(v) for 5 times only not 20 times.

microchip78
  • 2,040
  • 2
  • 28
  • 39
  • 1
    That is expected and has to do with change detection and how *ngFor does rendering. You should not use non idempotent computed values in your loop, rather a static list that only changes when your code decides it has to change (ie. like an add new click or remove click or edit click etc). – Igor Aug 30 '17 at 11:16
  • but this is causing big issue for me when i have components within components within components ... it is repeating for indefinite time ... is there any way to stop it once all elements rendered ? – microchip78 Aug 30 '17 at 11:17
  • Are you rendering dynamic components inside the `*ngFor`? – Igor Aug 30 '17 at 11:18
  • See https://stackoverflow.com/questions/45880950/angular-2-4-call-function-for-each-row-in-ngfor/45881293#45881293 – Günter Zöchbauer Aug 30 '17 at 11:20
  • yes I am using dynamic components – microchip78 Aug 30 '17 at 11:20
  • See [Dynamically adding components in ngFor](https://stackoverflow.com/questions/42274281), there are also some additional related [so] question/answers in the comments of this linked question. – Igor Aug 30 '17 at 11:22
  • Awesome guys .. thanks ... This issue was driving me crazy ... – microchip78 Aug 30 '17 at 18:32

0 Answers0