1

I have this cart component that I use for getting the cart data from the back end.

import { Component, OnInit } from '@angular/core';

import { CartService } from './cart.service';

@Component({
    selector: 'cart',
    templateUrl: './cart.component.html',
    styleUrls: ['./cart.component.css']
})

export class CartComponent implements OnInit{
    carts: any;
    cartItems: any;
    totalPrice: Number;

    constructor(private _cartService: CartService){};

    ngOnInit(){
        this.getItems();
    }

    getItems(){
        this._cartService.getCartItems(localStorage.getItem('currentUserId'))
            .subscribe((cart) => {
                this.cartItems = cart.products;
                this.totalPrice = cart.totalPrice;
                this.carts = cart;
                console.log(this.carts)
            },
            (err) => console.log(err));
    }
}

This is my object values.

enter image description here

I put all the products inside cartItems as shown on my component and loop it in my template using *ngFor

<tbody *ngFor="let cartItem of cartItems">

This is the result

enter image description here

Now I want to update the quantity of one item, press the refresh button beside the remove button then it will send just the product details that I have the refresh button pressed to my back end.

Can someone help me on how to make it happen?

2
  • What is not working? Commented Jan 10, 2017 at 0:24
  • I need to get the object value from an array. for example the product Fast, i will update the quantity to 10, how can I get that from an *ngFor array? Commented Jan 10, 2017 at 0:28

1 Answer 1

5

On click pass the cartItem in to the function called on click.

<tbody>
    <tr *ngFor="let cartItem of cartItems">
      <td>{{cartItem.product}}</td>
      <td>{{cartItem.size}}</td>
      <td>{{cartItem.price}}</td>
      <td>{{cartItem.quantity}}</td>
      <td>{{cartItem.subtotal}}</td>
      <td><button (click)="onClick($event, cartItem)">Refresh Button</button></td>
    </tr>
</tbody>

Now, in the component class use the cartItem

onClick(event, cartItem){
   console.log(cartItem); // here your cart item object will be shown
   // do your stuff here with your cartItem
}
Sign up to request clarification or add additional context in comments.

2 Comments

what is the $event for?
If you want to do anything with the target element, you can do it with it useng event.target in the function. Just added for future uses. But currently, it is nothing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.