Issue
Say i have the following object array, lets name it itemArray;
{
"totalItems": 2,
"items": [
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "bar"
},
]
}
And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?
What i would like is something like the example below;
updateUser(user){
this.myservice.getUpdate(user.id)
.subscribe(newitem => {
this.updateArray(newitem);
});
}
updateArray(newitem){
this.itemArray.items[newitem.id].name = newitem.name
}
or even better, replacing the entire object;
updateArray(newitem){
this.itemArray.items[newitem.id] = newitem
}
This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?
Template requested in comment:
<tr *ngFor="let u of itemsArray.items; let i = index">
<td>{{ u.id }}</td>
<td>{{ u.name }}</td>
<td>
<input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
<label for="singleCheckbox-{{i}}"></label>
</td>
</tr>
Solution
I have created this Plunker based on your example that updates the object equal to newItem.id
Here's the snippet of my functions:
showUpdatedItem(newItem){
let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);
let index = this.itemArray.items.indexOf(updateItem);
this.itemArray.items[index] = newItem;
}
findIndexToUpdate(newItem) {
return newItem.id === this;
}
Hope this helps.
Answered By - Nehal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.