Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: View not updating on array push

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);
}
like image 846
LadyT Avatar asked Jan 23 '17 18:01

LadyT


1 Answers

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];
}
like image 116
David Sajdl Avatar answered Nov 11 '22 02:11

David Sajdl