Question presented to candidate:
"Our product table uses *ngFor and polls the API every few seconds. Users complain the table flickers and loses their selection. What is trackBy, how would it help, and what is its equivalent in modern Angular?"
What a strong answer should cover:
- By default
*ngFortracks items by object identity, so an API response full of new objects looks like a completely new list: every row is destroyed and recreated. trackByis a function(index, item) => keythat tells the differ which items are "the same", so existing rows are kept and only their bindings update.- Benefits: fewer DOM operations, preserved focus/selection/input state, child components keep their state, CSS transitions do not restart.
- The key must be stable and unique (an id), not the index for lists that reorder.
- Gotcha: the function is called with
thisbound to the differ, not the component, so use an arrow function or avoidthis. - Modern Angular:
*ngForis deprecated since v20;@formakes the same idea mandatory withtrack item.id.
Clarifying questions expected:
- "Do the items have a unique id from the backend?"
- "Is the app still on
*ngFor, or can we move this table to@for?"
Code / implementation expected: Yes β a trackBy function on the component and its use in the template.