Check out our Angular Book Series.

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:


@Input() items: Array<items>;

The view of the component would loop over the array:


<div *ngFor="let item of items">
{{ item.data }}
</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:


items.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:


items = 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.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.