MrNew MrNew - 14 days ago 4
Javascript Question

Angular2 how to delete element in ngFor

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.

updateOrder(id) {
console.log('Delete from Prepare Panel', id);
}

Answer

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.