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
Using TrackBy with ngFor in Angular
📖 Scenario: You are building a simple Angular component that shows a list of books. Each book has an id and a title. You want to display the list efficiently and avoid unnecessary re-rendering when the list changes.
🎯 Goal: Create an Angular standalone component that displays a list of books using *ngFor. Add a trackBy function to help Angular track each book by its id for better performance.
📋 What You'll Learn
Create a list of books as an array of objects with id and title
Add a variable to hold the list of books
Write a trackByBookId function that returns the id of a book
Use *ngFor with trackBy in the template to display the books
💡 Why This Matters
🌍 Real World
Using <code>trackBy</code> in Angular helps large lists update efficiently without re-rendering unchanged items, improving app speed and user experience.
💼 Career
Understanding <code>trackBy</code> is important for Angular developers to optimize performance in real-world applications with dynamic lists.
Progress0 / 4 steps
1
Create the books array
Create a variable called books as an array with these exact objects: { id: 1, title: 'Angular Basics' }, { id: 2, title: 'TypeScript Essentials' }, and { id: 3, title: 'RxJS in Depth' }.
Angular
Hint
Use square brackets [] to create an array and curly braces {} for each book object.
2
Add the trackBy function
Add a function called trackByBookId that takes index and book as parameters and returns the id property of the book.
Angular
Hint
The function should return the id of the book to help Angular track each item.
3
Use ngFor with trackBy in the template
In the component template, use *ngFor to loop over books. Add trackBy: trackByBookId to the *ngFor directive. Display each book's title inside a <li> element.
Angular
Hint
Use <ul> and <li> tags. The *ngFor directive should include trackBy: trackByBookId.
4
Make the component standalone and import CommonModule
Add the @Component decorator with standalone: true. Include CommonModule in the imports array. Add selector as 'app-book-list' and put the template with the *ngFor inside the template property.
Angular
Hint
Use backticks ` for the template string. Import CommonModule from @angular/common.
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
Step 1: Understand what ngFor does
ngFor repeats a template for each item in a list, rendering them in the view.
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.
Final Answer:
To improve performance by uniquely identifying list items during updates -> Option A
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
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.
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.
Final Answer:
*ngFor="let item of items; trackBy: trackByFn" -> Option B
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?
<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
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.
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.
Final Answer:
Only the new item is rendered and logged -> Option D
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
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.
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.
Final Answer:
It returns a non-unique value causing incorrect tracking -> Option A
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
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.
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).