Why didn't my Angular View Update when I added items to the input array?

I was recently working on an Angular project where the view had an input array:

view plain print about
1@Input() items: Array<items>;

The view of the component would loop over the array:

view plain print about
1<div *ngFor="let item of items">
2 {{ item.data }}
3 </div>

At some point in the app, user interaction happens, and the app needs to load more data. We had a result handler from a service call doing something like this:

view plain print about
1items.push(...itemsToAdd)

If you output the results, you'll see that the items array had the new items. Try it here.

However, the view would not update the display to reveal the new items in the array. How come?

In short, the view did not know that it needed to update itself. The view contains a pointer to the array and was watching for changes to that pointer. While the items in the array changed, the array pointer did not. An easy solution was to change the way items were added to the new array:

view plain print about
1items = items.concat(itemsToAdd)

Since we were updating the actual input value, the view would know that the item had changed, triggering a redraw of the screen.

That's how we handled it!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)

Comments are not allowed for this entry.