Why ngFor does not need keys like in Vue and React?

621 Views Asked by At

I have just started with Angular couple of weeks ago. In Vue and React we always use a unique key when we render an array of elements, for a more efficient rendering, specially when the elements and order or amount of them changes it's useful. Therefore create-react-app or Vue CLI would always yell at you if you forget assigning the key property on elements.

But why there's no such warning or error in Angular? And how angular manages to render a list and changes on it without a key property on list elements efficiently?

Key in Vue's v-for : https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
Keys in React's map: https://reactjs.org/docs/lists-and-keys.html#keys

1

There are 1 best solutions below

0
Octavian Mărculescu On BEST ANSWER

Angular uses object identity to track insertions and deletions within the iterator and reproduce those changes in the DOM.

[...]

The identities of elements in the iterator can change while the data does not. This can happen, for example, if the iterator is produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response produces objects with different identities, and Angular must tear down the entire DOM and rebuild it (as if all old elements were deleted and all new elements inserted).

To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the trackBy option to NgForOf. trackBy takes a function that has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.

In short, you don't necessarily need it. If you know your object identities will change and superfluous rendering is going to happen, then you can provide your own trackBy function and decide for yourself when an element should be re-rendered.

I got the quotes from this documentation link.