Bird
Raised Fist0
Angularframework~5 mins

TrackBy in ngFor in Angular - Cheat Sheet & Quick Revision

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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:
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.

      Practice

      (1/5)
      1. What is the main purpose of using trackBy in an ngFor directive in Angular?
      easy
      A. To improve performance by uniquely identifying list items during updates
      B. To style list items differently based on their index
      C. To sort the list items before rendering
      D. To filter out duplicate items from the list

      Solution

      1. Step 1: Understand what ngFor does

        ngFor repeats a template for each item in a list, rendering them in the view.
      2. Step 2: Identify the role of trackBy

        trackBy helps Angular know which items changed by uniquely identifying them, so it only updates those items instead of re-rendering the whole list.
      3. Final Answer:

        To improve performance by uniquely identifying list items during updates -> Option A
      4. Quick Check:

        TrackBy improves performance = C [OK]
      Hint: TrackBy helps Angular track items uniquely for faster updates [OK]
      Common Mistakes:
      • Thinking trackBy sorts or filters items
      • Believing trackBy changes item styles
      • Assuming trackBy removes duplicates
      2. Which of the following is the correct syntax to use trackBy in an ngFor loop?
      easy
      A. *ngFor="let item of items; trackByFn"
      B. *ngFor="let item of items; trackBy: trackByFn"
      C. *ngFor="let item of items; trackByFn()"
      D. *ngFor="let item of items; trackBy=trackByFn()"

      Solution

      1. Step 1: Recall the correct ngFor syntax with trackBy

        The correct syntax uses a semicolon and the keyword trackBy followed by the function name without parentheses.
      2. Step 2: Compare options

        *ngFor="let item of items; trackBy: trackByFn" matches the correct syntax: *ngFor="let item of items; trackBy: trackByFn". Others either miss the keyword or use parentheses incorrectly.
      3. Final Answer:

        *ngFor="let item of items; trackBy: trackByFn" -> Option B
      4. Quick Check:

        Correct syntax includes 'trackBy:' keyword [OK]
      Hint: Use 'trackBy:' keyword with function name, no parentheses [OK]
      Common Mistakes:
      • Omitting 'trackBy:' keyword
      • Adding parentheses after function name
      • Using '=' instead of ':'
      3. Given the component code below, what will be logged when the items array is updated by adding a new item?
      items = [{id: 1, name: 'A'}, {id: 2, name: 'B'}];
      
      trackByFn(index: number, item: any) {
        return item.id;
      }

      Template:
      <div *ngFor="let item of items; trackBy: trackByFn">{{item.name}}</div>
      medium
      A. Rendering throws an error due to trackBy function
      B. All items are re-rendered and logged
      C. No items are rendered
      D. Only the new item is rendered and logged

      Solution

      1. Step 1: Understand how trackBy works with unique IDs

        The trackByFn returns the unique id of each item, so Angular can track items by their IDs.
      2. Step 2: Effect of adding a new item

        When a new item is added, Angular uses trackByFn to detect only the new item and renders just that one, not the entire list.
      3. Final Answer:

        Only the new item is rendered and logged -> Option D
      4. Quick Check:

        trackBy with unique ID renders only changed items [OK]
      Hint: trackBy returns unique id to render only changed items [OK]
      Common Mistakes:
      • Assuming all items re-render on update
      • Thinking trackBy causes errors if function returns id
      • Believing no items render after update
      4. Identify the error in the following trackBy function used in an ngFor loop:
      trackByFn(index: number, item: any) {
        return index + 1;
      }
      medium
      A. It returns a non-unique value causing incorrect tracking
      B. It returns the index which is acceptable and error-free
      C. It throws a syntax error due to missing return type
      D. It causes Angular to ignore the trackBy function

      Solution

      1. Step 1: Analyze the returned value from trackByFn

        The function returns index + 1, which changes if the list order changes or items are added/removed.
      2. Step 2: Understand why this causes problems

        Returning a value based on index is not stable for tracking because indexes shift, causing Angular to think items changed incorrectly.
      3. Final Answer:

        It returns a non-unique value causing incorrect tracking -> Option A
      4. Quick Check:

        trackBy must return stable unique IDs, not shifting indexes [OK]
      Hint: trackBy must return stable unique IDs, not changing indexes [OK]
      Common Mistakes:
      • Thinking index is always safe to return
      • Ignoring that indexes shift on list changes
      • Assuming missing return type causes syntax error
      5. You have a list of users with possible duplicate names but unique IDs. You want to optimize rendering with trackBy. Which trackBy function below correctly handles this scenario to avoid unnecessary re-renders when the list updates?
      hard
      A. trackByFn(index: number, user: any) { return user.name; }
      B. trackByFn(index: number, user: any) { return index; }
      C. trackByFn(index: number, user: any) { return user.id; }
      D. trackByFn(index: number, user: any) { return user; }

      Solution

      1. Step 1: Identify the unique property for tracking

        Users may have duplicate names, so using user.name is not reliable. The unique user.id is the best choice.
      2. Step 2: Evaluate each option

        A uses user.name (not unique), B uses user.id (stable and unique), C uses index (unstable), D returns the whole user object (not recommended).
      3. Final Answer:

        trackByFn(index: number, user: any) { return user.id; } -> Option C
      4. Quick Check:

        Use unique IDs for trackBy to avoid re-renders [OK]
      Hint: Always trackBy unique stable IDs, not names or indexes [OK]
      Common Mistakes:
      • Using non-unique properties like names
      • Using index which changes on list updates
      • Returning the whole object causing errors