Yesterday, I sent you 3 different examples of Angular binding syntaxes and asked you to take a look at them and identify the pros and cons of each one.
Today, let’s cover the pros and cons of our first example:
Example #1 – Array of data
<div *ngFor="let data of getData()">
The only pro of this example is the simplicity of the syntax. Other than that, the syntax uses one of the anti-patterns covered earlier in this newsletter: Calling a method in a template. The problem is that this method will be called a lot more than you’d think, and if that code happened to create a new array every single time, it could be really bad in terms of performance, as Angular would have to re-render the entire list pretty much every time the user does anything in the application.
What can we do to improve it?
- Use a variable instead of a method – this fixes the performance issue right away:
<div *ngFor="let data of dataList">
- Use a trackBy function to avoid useless re-renders. By telling Angular what’s the unique ID of each list item, Angular would be less confused, but it’s a sub-par solution:
<div *ngFor="let data of getData(); trackBy: trackById">
Conclusion
If you want to iterate over data that’s in your component (not an observable or a Signal), then use a variable instead of calling a method. Easy enough.