Reputation: 741
I have a question without any code. I read somewhere that the view only updates when some of the variables change their reference. But how does it work with arrays? When I edit an array, sometimes the view updates, sometimes not. Is there any way to refresh the view after an array change? Right now I use :
data =JSON.parse(JSON.stringify(data))
to get a new reference for the data array. Is this correct? Is there any better way to do that ?
Upvotes: 4
Views: 13736
Reputation: 8421
In Angular, you need to learn how change detection works, because it affects the way how you treat your objects and components. There are several good articles about it. Maximus mentioned one, you can take a look at this blog: https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
With the array, it's hard to detect internal changes, so you should make a shallow copy of the array if you modify its content. The shallow copy means that the content of the array stays the same (same objects in a memory), but the array object is new. There are several ways how to do it:
const shallowCopy1 = [...originalArray];
const shallowCopy2 = originalArray.slice(0);
The JSON stringify+parse creates a deep copy of the array and its content (new objects in a memory), which is not necessary in your case.
There is also a concept of keeping you whole application model immutable (you don't modify it after its creation - you create a new copy when modification is needed). Check this article or the ngrx project. It can be interesting for you if you need to build a more complicated application.
Upvotes: 8