What is the use of ngForTrackBy directive?

Member

by adolf , in category: Technology , 3 years ago

What is the use of ngForTrackBy directive?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by braeden , 3 years ago

For iterating over a collection in Angular 2, the ngFor directive is used which instantiates a template once per item from the collection. If a data needs to be changed at some point in the collection, then a problem occurs because angular cannot keep a track of items in the collection and has no knowledge of the items which were added or deleted. This results in the deletion of all the DOM elements that are associated with the data and are again created. If the collection is big, then it becomes more complicated because a lot of DOM manipulation occurs which are expensive. So, to solve this problem, a trackBy function is used which takes the index and the current item as arguments and returns the unique identifier for this item.