Angular

Deep Dive into Angular 17 @for() Directive: Using Track and TrackBy

4 min. read

Angular 17 brings forth exciting features and enhancements, making it easier and more efficient to build dynamic web applications. One such feature is the @for() directive, coupled with track or trackBy, which empowers developers to iterate through collections with ease while optimizing performance. In this guide, we'll delve into the basics of using @for() and explore how track and trackBy can enhance the rendering process.

What is the @for() Directive?

In an earlier post, we explored the @for() directive and its benefits. Like its predecessor *ngFor, @for() allows developers to iterate over collections, such as arrays or objects, and dynamically render HTML elements based on each item in the collection. This directive simplifies the process of displaying dynamic data in templates.

In the below snippet, items is the array or iterable object over which we want to iterate, and item represents the current item in each iteration.

<element *for="let item of items">
  <!-- HTML template to be repeated for each item -->
</element>
Syntax of @for()

The Importance of track

Performance optimization is crucial when working with dynamic lists or tables in Angular, especially when dealing with large datasets. By default, Angular re-renders the entire list whenever a change is detected, which can be inefficient and impact performance.

This is where track comes in. Track is a feature that helps Angular identify unique items in a collection, allowing it to track changes more efficiently and re-render only the elements that have been modified.

Implementing track

Suppose we have an array of user objects with unique IDs:

users = [
  { id: 1, name: 'Justin' },
  { id: 2, name: 'Keith' },
  { id: 3, name: 'Eric' },
];

To use track, you need to define a function in your component that identifies each item uniquely. This function should return a unique identifier for each item.

trackById(index: number, item: any): any {
  return item.id; // Assuming each item has a unique 'id' property
}
@for() with track: Function for track

In your template, you can then specify the track function within the @for() directive:

<element *for="let item of items; track: trackById">
  <!-- HTML template -->
</element>
@for() with track 

Or simply combine the two snippets (note the absence of a colon : after track):

<element *for="let item of items; track item.id">
  <!-- HTML template -->
</element>
@for() with track (simplified without function)

By providing Angular with a way to track individual items using track, you significantly improve the efficiency of list rendering, especially when dealing with large datasets or frequent updates.

What about trackBy?

trackBy is a function that helps Angular identify unique items in a collection, like track.

Implementing trackBy

Suppose we have an array of user objects with unique IDs:

users = [
  { id: 1, name: 'Cortney' },
  { id: 2, name: 'Kim' },
  { id: 3, name: 'Sam' }
];

To use trackBy, you need to define a function in your component that identifies each item uniquely. This function should return a unique identifier for each item.

trackByFn(index: number, item: any): any {
  return item.id; // Assuming each item has a unique 'id' property
}

In your template, you can then specify the trackBy function within the @for() directive:

<element *for="let item of items; trackBy: trackByFn">
  <!-- HTML template -->
</element>

When to Use track

The track option is suitable when:

  1. Simple Iterations: You're iterating over a simple collection of items without needing to identify individual items by a unique property.
  2. Static Data: Your data doesn't change frequently, and you don't anticipate changes that could affect the rendering of individual items.
  3. Performance is Not a Concern: You're working with small datasets or your application's performance requirements are not stringent.

When to Use trackBy

The trackBy function is more appropriate in scenarios where:

  1. Dynamic Data: Your collection of items frequently changes, and you want to optimize the rendering process to improve performance.
  2. Identifying Individual Items: Each item in your collection can be uniquely identified by a specific property (such as an ID).
  3. Efficient DOM Manipulation: You want Angular to only re-render elements that have changed rather than re-rendering the entire list when updates occur.
  4. Large Datasets: You're working with large datasets where rendering efficiency becomes critical for maintaining smooth application performance.

Example Scenarios

  • Using track: If you have a static list of items that rarely changes and doesn't need to be uniquely identified, using track is simpler and sufficient.
  • Using trackBy: In cases where you're dealing with dynamic data, such as a list of user comments where each comment has a unique ID, using trackBy with a function that returns the ID would be ideal. This ensures that Angular efficiently tracks changes and updates only the necessary elements in the DOM.

Conclusion

In Angular 17, the @for() directive, coupled with track or trackBy, offers a powerful mechanism for efficiently iterating through collections and rendering dynamic content. Developers can build more responsive and high-performing web applications by understanding how to leverage these features.

With this guide, you should now feel confident in incorporating @for() and track or trackBy into your Angular projects, making your code more efficient and your applications more responsive. To learn the benefits of using @for(), check out this post explaining its many advantages for both the developer and the users. Happy coding!

To share additional thoughts on the latest Angular release, please reach out to us via Twitter, LinkedIn, or send us a message.

Kim Pham

Senior Front-end Web Developer