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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With