2

I have an array of objects with properties name and age. Name of the array is person.

Problem is when i update the property of an element of array as :

this.person[0].name = "godfather";

original array is updated but component view remains as it is. I figured out the problem is angular change detection doesn't consider updation inside an array as a change. So, i tried below statement (changes reference to array):

this.person = this.person.slice();

I just want to know, Is using the later statement a good practice or there is some better approach to deal with the above problem?

1

2 Answers 2

1

It depends on the cost of this slice() operation. If it's for small arrays it might not cause any harm but if it is for large arrays it may cause notable performance issues. In this case using an observable that notifies the receiver actively about changes is a better way.

Sign up to request clarification or add additional context in comments.

5 Comments

What would be a better solution?
An observable or using IterableDiffer github.com/angular/angular/blob/…, perhaps others. Depends on the concrete use case.
I cannot replicate your problem. See stackblitz.com/edit/angular-5sa3pe. What should I change to replicate it
Another one where I am passing array of objects to child component stackblitz.com/edit/angular-qqvpsd
@GünterZöchbauer I have added a question as well to elaborate my concern stackoverflow.com/questions/56200638/…
1

Your approach is an unspecified use of slice that may work with some but not all JS implementations. I have used this with success:

this.person = JSON.parse(JSON.stringify(this.person));

6 Comments

This seems rather expensive in compairson. Do you you have a link that provides more information about where slice() might not work?
The JSON approach is more expensive, yes. However, if it's only used in UI and not in loops or otherwise time-critical code I don't see a problem. According to the specification slice needs at least one parameter. Calling it with no parameter is not specified.
Just slice(0) would do then I guess as well?
I haven't tried it but yes that should work and would be less expensive. The JSON approach I have tried and it works.
Also, slice only performs a shallow copy. If the array contains objects slice won't work for this purpose. In fact, if I understand the OP correctly, it is an array of objects and that's why it won't work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.