Does ng-repeat save DOM elements or create new ones when changing collections?

I saw a lot of questions about the order in which ng-repeat ends compared to other directives or things happening on the Angular ground, but I could not find an answer to how exactly it does this.

I have two ideas on how this might work.

The first way: When the ng-repeat trigger tracks, it deletes all elements created from the DOM, then creates all new elements in their place, even if many of these elements are the same (for example, in the case of 1 element added to the substitution array).

The second way:. Since ng-repeat already tracks which items come with items in its collection, it simply removes items that no longer exist in the collection, and creates new items for items that are new to the collection.


What is this and why?

+6
source share
1 answer

This is the second way: Angular is trying to be smart in creating / deleting DOM elements :

The ngRepeat directive provides a way to visualize a collection of elements specified by a template. To do this, AngularJS compiles the given template and then clones it for each unique element in the collection. Because the collection is mutated by the controller, AngularJS adds, deletes, and updates the corresponding DOM elements as needed.

But how does AngularJS know what actions to perform when? If you start testing rendering, you will find that AngularJS does not create a DOM to force work; that is, it does not recreate the DOM for each rendering. Instead, it only creates a new DOM element when an entirely new element is entered into the collection. If the existing item is updated, AngularJS simply updates the corresponding DOM properties, rather than creating a new DOM node.

This can still affect performance unnecessarily, i.e. when passing items by value in a collection (thereโ€™s a great example of this in the blog post above). Therefore, Angular has supported "track by" for ngRepeat since version 1.2: a way to help Angular decide when to create a DOM:

With this association in place, AngularJS will not $ destroy and recreate DOM nodes unnecessarily. This can have tremendous performance and user friendliness.

Official documentation reports :

You can also provide an additional tracking function that can be used to associate objects in a collection with DOM elements. If no tracking function is specified, ng-repeat binds items by ID in the collection.

For example: item in items track by item.id is a typical template when items come from the database. In this case, the identifier of the object does not matter. Two objects are considered equivalent if their id property is the same.

+6
source

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


All Articles