Nested ngFor and trackBy, array comparison

I have a big project, there I have 4 nested * ngFor. So the creation is about 200 lines, I think sharing would not help, so I will explain it as best as possible. The problem is that after updating the object, the elements will be destroyed and recreated. Which leads in productivity (nothing matters in just 0.5 seconds) and scroll back. And this is my problem, I do not want this to happen.

Array:

array[0-X] = For Paginator array[X][1-3] = contains 3 columns // #Column array[X][X][1-9] = divides the column in 9 blocks // #InfoBlock array[X][X][X][1-X] = the content of the single blocks // #Info 

After creation, the user can only move the #Info element over his settings, wherever he wants.

As an example, move #Info to another #InfoBlock. Through a subscription, I save the changes to the database and reloads the entire array.

Like this:

 this.pageinator = result; 

Now it destroys the divs and creates them new ones, this causes my layout to scroll up. I tried trackby, but the reason for the whole array was overwritten, and this will not work.

Question: Is there a way to compare 2 arrays and just make changes to the previous one. I know that I cannot reload the data, but this can cause problems because the software is not used by only one user.

Edit: example

 array[0][1][1][1] = "Content X" array[0][1][2][2] = undefined // After reloading array[0][1][1][1] = undefined array[0][1][2][2] = "Content X" // Now I want Angular to just change this 2 elements, cause the others stay the same. 

Edit 2: I found out sometimes:

 this.pageinator = result; 

Automatically accept changes. This happens 1 out of 10 times.

+5
source share
1 answer

Since you are manipulating a sheet change event inside an array, why not switch the values ​​inside the array by position? You switch the values ​​between array[0][1][1][1] and array[0][1][2][2] in the array, and *ngFor updates the view.

I dropped a simple plunkr here

Edit

If only leaves change on your array and the elements of the main array remain in the same position, then you have an easy mission of comparing elements by position and switching elements, since the leaves are different, for example:

 //this assumes that main array won't change - same length and position for (let i=0; i < originalArray.length; i++) { if (originalArray[i][leafindex] !== newArray[i][leafindex] { originalArray[i] = newArray[i]; } } 

If the main array changes the length or position of the elements, implementing comparisons to look for changes has become difficult and prone to slow performance. In this case, I will advise you to do this, as now, with rewriting the array, but before changing the data, take the scrollTop value and apply the same scroll after re-rendering the elements.

+1
source

Source: https://habr.com/ru/post/1269825/


All Articles