0
0
Angularframework~5 mins

TrackBy in ngFor in Angular - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the trackBy function in ngFor?
The trackBy function helps Angular identify items in a list uniquely, so it can efficiently update only the changed items instead of re-rendering the whole list.
Click to reveal answer
beginner
How do you define a trackBy function in Angular?
A trackBy function takes two arguments: the index and the item. It returns a unique identifier (like an ID) for each item to help Angular track it.
Click to reveal answer
intermediate
Why is using trackBy important for large lists?
Using trackBy improves performance by preventing Angular from recreating all DOM elements when the list changes. It updates only the changed items, saving time and resources.
Click to reveal answer
intermediate
What happens if you don't use trackBy with ngFor?
Without trackBy, Angular treats every change as a new list and recreates all DOM elements, which can cause slow rendering and loss of element state like input focus.
Click to reveal answer
beginner
Show a simple example of a trackBy function for a list of users with unique id properties.
Example:<br>
trackByUserId(index: number, user: any): number {
  return user.id;
}
Click to reveal answer
What does the trackBy function return?
AA boolean value
BA unique identifier for each item
CThe index only
DThe whole item object
Why should you use trackBy with ngFor?
ATo add animations
BTo sort the list automatically
CTo filter items in the list
DTo improve rendering performance by tracking items uniquely
What arguments does a trackBy function receive?
AIndex and item
BOnly the item
COnly the index
DNo arguments
If you don't use trackBy, what might happen when the list changes?
AAngular recreates all DOM elements
BAngular updates only changed items
CAngular throws an error
DNothing happens
Which of these is a valid trackBy function signature?
A() => number
B(item: any) => void
C(index: number, item: any) => any
D(index: string) => string
Explain how the trackBy function improves performance in Angular's ngFor directive.
Think about how Angular updates the list in the browser.
You got /4 concepts.
    Describe how to write a trackBy function for a list of objects with unique IDs.
    Focus on the function signature and return value.
    You got /3 concepts.