2017-01-10 80 views
1

我有用于从后端获取购物车数据的此购物车组件。从angular2 * ngFor数组获取特定值

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)); 
    } 
} 

这是我的对象值。

enter image description here

我把所有的内部cartItems产品我的组件,并使用循环在我的模板* ngFor

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

在如图所示这是结果

enter image description here

现在我想更新一个项目的数量,按下删除按钮旁边的刷新按钮,然后它会发送j在产品详细信息中,我已将刷新按钮按下到我的后端。

有人可以帮助我如何使它发生?

+0

什么是不工作? –

+0

我需要从数组中获取对象值。例如产品Fast,我会将数量更新为10,我如何从* ngFor数组中获取? –

回答

5

点击将cartItem传递给点击函数。

<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> 

现在,在组件类使用cartItem

onClick(event, cartItem){ 
    console.log(cartItem); // here your cart item object will be shown 
    // do your stuff here with your cartItem 
} 
+0

什么是$事件? –

+0

如果你想对目标元素做任何事情,你可以在函数中使用'event.target'来完成。只是添加为未来的用途。但目前,这没什么 –