11

I have two child components. They are sharing data from a json file that I am loading using the http.get/subscribe method. For some reason, when I push data into the array, it doesnt update in the view. It shows the updated array in the console though.

app component loading the data from a service

this.dataService.getData()
 .subscribe(
     data => {
       this.data = data;
     },
     (err) => console.log('Error: ', err),
     () => console.log("success!")
   );

I am using inputs to access the data in my child component. Are there any ways in Angular 2 to update the view when new values are pushed into the array.

Display Component

<div *ngFor="let i of items; let k = index"><h1>{{i.title}}</h1> <p>{{i.desc}}</p></div>

The Button Component

<button (click)="addItem(i)">Add Item</button>

The Component Function
addItem(i){
  let data = {title: "Some title", desc: "Some desc"};
  this.data.list[i].items.push(data);
}
17
  • 1
    Can you show us the component code? What you posted looks correct; the problem might be elsewhere. Commented Jan 23, 2017 at 18:55
  • 1
    are you using the OnChanges lifecycle hook? You might need to call that if you're doing some more work on the update to "data" :) Commented Jan 23, 2017 at 19:09
  • 1
    @SteveG. I added the code that I am using. A display component to display the data, and a button to push data into the array. Commented Jan 23, 2017 at 20:19
  • 2
    ngFor iterates over items not data Commented Jan 23, 2017 at 20:49
  • 4
    Possible duplicate of Why angular 2 ngOnChanges not responding to input array push Commented Mar 15, 2018 at 15:20

1 Answer 1

12

I have the same problem and I solved this by using spread operator to create a new array of the object rather than to push new element into an existing array.

in your case I would do something like:

addItem(i){
  let data = {title: "Some title", desc: "Some desc"};
  this.data.list[i].items = [...this.data.list[i].items, data];
}
Sign up to request clarification or add additional context in comments.

1 Comment

isn't that the same idea of "concat" ?

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.