【问题标题】:Getting a specific value from an angular2 *ngFor array从 angular2 *ngFor 数组中获取特定值
【发布时间】:2017-01-10 00:08:27
【问题描述】:

我有这个购物车组件,用于从后端获取购物车数据。

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

这是我的对象值。

我将所有产品放入我的组件上显示的 cartItems 中,并使用 *ngFor 在我的模板中循环它

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

这是结果

现在我想更新一件商品的数量,按下删除按钮旁边的刷新按钮,然后它只会将我按下刷新按钮的产品详细信息发送到我的后端。

有人可以帮我实现它吗?

【问题讨论】:

  • 什么不起作用?
  • 我需要从数组中获取对象值。例如产品 Fast,我会将数量更新为 10,如何从 *ngFor 数组中获取?

标签: angular


【解决方案1】:

点击时将 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
}

【讨论】:

  • $event 有什么用?
  • 如果你想对目标元素做任何事情,你可以在函数中使用 event.target 来做。刚刚添加以供将来使用。但目前,它什么都不是
猜你喜欢
  • 2018-04-01
  • 2017-08-28
  • 2017-09-05
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多