2017-01-10 79 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'來完成。只是添加爲未來的用途。但目前,這沒什麼 –