简体   繁体   中英

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);
}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM