ngFor generating many calls

Asked

Viewed 45 times

0

I have an array that contains 40 positions. By making an ngFor using this array, I create a series of components within this *ngFor. The problem is, it’s killing the performance. Debugging, and doing a counter inside that is, I found that it runs 600x, having only 40 items.

Reading about it, I discovered that it is Change Detection, but I couldn’t solve it. Does anyone know how to get around this behavior? (I can’t turn off the change).

In the file . ts

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

  ngOnInit() {
    let i = 0;

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

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

In html

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

Observing on the console, you will see that the counter goes up to 400.

If you resize the screen, for example, it still generates over 400 calls :o

  • Related possible: https://answall.com/questions/325996/angular-6-ngfor/326158#326158

  • Hello @Weber Welcome to Stackoverflow, please add some code snippets to make the question clearer and so we can check if there is a problem in your code, I suggest you read https://answall.com/help/mcve

  • Hello Pedro, all right? Thanks for trying to help. It is exactly in this post that suggested that I discovered that change Detection was generating the console.log the most, but I can’t disable it. I would like to know if there is any technique to get around this problem.

  • 1

    @Lucasduete, I edited the post for better understanding, thanks for the tips of the complete minimum verifiable.

1 answer

0

This happens because of Change Detection as already mentioned.

Each time you add to the array, it detects and runs ngFor* once more. It’s like it’s 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 that I put in, you will see that the total Checkout will be 820, which is the total of iterations that ngFor* will run in the code you did.

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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.