0
0
Angularframework~30 mins

TrackBy in ngFor in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use backticks ` for the template string. Import CommonModule from @angular/common.