ngFor generating many calls

0

I have an array that contains 40 positions. When doing a ngFor using this array, I create a series of components within that * ngFor. The problem is that it's putting an end to the performance. Debugging, and doing a counter within that, I found that it runs 600x, having only 40 items.

Reading on, I discovered that this is Change detection, but I could not solve it. Does anyone know how to circumvent this behavior? (I can not turn off the change detection).

In the .ts file

  cont: number = 0;
  array: number[] = [];

  ngOnInit() {
    let i = 0;

    while(i < 40) {
      this.array.push(i);
      i++;
    }
  }

  contador() {
    console.log(this.cont);
    this.cont++;
  }

No html

<div *ngFor="let numb of array">
  <!-- Imaginem aqui muitos outros componentes que executam várias funções -->
  <p>{{ contador() }}</p>
</div>

Looking at the console, you'll see that the counter goes up to 400.

If you resize the screen, for example, it still continues to generate 400 more calls:

    
asked by anonymous 17.10.2018 / 21:56

1 answer

0

This is because of Change detection as already mentioned.

Each time you add it to the array, it detects and runs ngFor * one more time. It's like the code below:

        let totalExecucao = 0;
        let array = [];

        for (int i = 0; i < 40; i++)
        {
            array.push(i);

            array.forEach(a => totalExecucao++);

            foreach (var item in array)
            {
                totalExecucao++;
            }
        }
        console.log(totalExecucao);

If you run this code I put it, you will see that the total execution will be 820, which is the total number of iterations that ngFor * will execute in the code you made.

Solution :

Create a temporary Array, include the objects in the temporary array, and then assign the temporary array to the one being used by ngFor *.

cont: number = 0;
array: number[] = [];
arrayTemp: number[] = [];

ngOnInit() {
  let i = 0;

  while(i < 40) {
    this.arrayTemp.push(i);
    i++;
  }
  array = arrayTemp;
}
    
02.11.2018 / 04:48