Reputation: 1424
How can I delete an element from an ngFor
? I have this ngFor
of items which has an Id
as well which I'm passing in the updateOrder()
function so It'd know which item I'm clicking.
getOrdersFromOrigin() {
this.sharedService.getOriginSite()
.subscribe(data => {
this.isLoading = false;
this.orderPreparing = data.Results
})
}
<div class="preparing" *ngFor="let prepare of orderPreparing">
<p> {{ prepare.Item }} </p>
<button class="btn btn-primary" (click)="updateOrder(prepare.Id)">It's Ready</button>
</div>
In my updateOrder
I don't have anything in my updateOrder function as I'm not sure how to delete an element relative to the Id
I pass in the (click)=""
event, it's giving me the Id
just fine.
This updateOrder()
is working as it removes it from the UI, but the idea is once its remove I want to add it to a collection.
updateOrder(id) {
for(let i = 0; i < this.orderPreparing.length; i++) {
if (this.orderPreparing[i].Id === id) {
this.orderPreparing.splice(i, 1);
this.addToCollection.push(this.orderPreparing[i]);
console.log(this.addToCollection);
console.log('Changed Status to AwaitingToPick');
break;
}
}
}
I've added a new private addToCollection = []
to push the removed item
to an array so I can add it in the collection. However the code above only takes the last index
when I add another one to the array it breaks the array becomes [Object{}, undefined]
Upvotes: 3
Views: 10098
Reputation: 5826
I guess what tou're looking for is deleting it from orderPreparing object (if you, of course, don't have a back-end for deleting it). You can try this one:
updateOrder(id) {
for(item in orderPreparing) {
if(item[id] == id) {
delete this.orderPreparing.item;
}
}
}
If you have a back-end app for it, you need to check if there is a script to delete the order on your back-end, made a function to call in your service which is responsible for the communication with your api, then include the service in your component, call a function to delete the order and update the orders once again.
Upvotes: 4
Reputation: 3906
There are multiple way to do this. Check out this, if I am not late:
updateOrder(id) {
for(let i = 0; i < this.orderPreparing.length; i++) {
if (this.orderPreparing[i].Id === id) {
this.orderPreparing.splice(i, 1);
break;
}
}
}
Hope will work for you.
Upvotes: 8