Skip to content
Advertisement

Update view when object has been pushed into array in Angular

I have an array of objects, I have added a click handler to manual test pushing an item into that array, It does that successfully, but what it does not do is update the view based on this. Do I need to put the method in the ngOnit? What I have so far just makes the object appear not based the click handler.

Code so far would be:

JavaScript

Binded to

JavaScript

But this works in the way of the object appearing already, not based on the click? I know putting the this.pushArray() into the ngOnit is not correct but just wanted to check it works and appears as it should if the user clicked and adde the item.

Advertisement

Answer

Even though the array’s content changed, the view is not updated because the times array has not changed from Angular’s change detection perspective, as the array is still in the same memory address (an array variable is a actually a reference). The solution is to reassign the array, thus changing its reference (“relocating” it to a different memory address) and trigger change detection. Like this:

JavaScript

For the same reason, in simple Typescript, you can do the following:

JavaScript

But you can’t do:

JavaScript

and instead do:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement