Angular2 - 如何对特定元素进行更改?

时间:2016-05-08 00:31:44

标签: angular

我的页面上有多个(添加到购物车)按钮,我设置了(添加到购物车)按钮以更改(单击),因此用户可以无缝地从购物车中添加删除项目。问题是,如果用户点击其中一个按钮,则所有按钮都会发生变化!仅仅因为代码无法识别用户点击的按钮。在正常情况下,应该更改的按钮是用户单击的唯一按钮! 但不幸的是,我不知道如何在Angular2中做到这一点。 谢谢你的帮助!

JS:

     addToCart(){
     if (this.amount == 0) {
        this.isCartEmpty = true;
     } else if  (this.amount > 0) {
         this.isCartEmpty = false;
     }   
     }

   addItem() {
    this.amount++;
  }
   removeItem() {
    this.amount--;
  }

HTML:

    <div *ngIf="isCartEmpty" (click)="addToCart()">ADD TO CART</div>
    <div *ngIf="!isCartEmpty" (click)="addToCart()"><div>

    <div>Element 1</div>
    <div (click)="removeItem()">-</div> 
    <div>{{amount}}</div> 
    <div (click)="addItem()">+</div>
    </div>

    <div>
    <div>Element 2</div>
    <div (click)="removeItem()">-</div> 
    <div>{{amount}}</div> 
    <div (click)="addItem()">+</div>
    </div>

    <div>
    <div>Element 3</div>
    <div (click)="removeItem()">-</div> 
    <div>{{amount}}</div> 
    <div (click)="addItem()">+</div>
    </div>

2 个答案:

答案 0 :(得分:1)

您可能应该将购物车创建为组件:

我-cart.component.ts

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

// Creating model here for simplicity. Should be in its own file

export class CartItem {
  public constructor(public name, public amount) { }

  public addItem() {
    this.amount++;
  }

  public removeItem() {
    if (this.amount > 0) {this.amount--};
  }
}

@Component({
  selector: 'my-cart',
  template:`
  <p>My Cart</p>
  <button (click)='addCartItem()'>Add Cart Item</button>a
  <button (click)='cleanCart()'>Clean Cart</button><br>
  <ul>
    <li *ngFor="let item of cartItems">
      {{item.name}}, Amount = {{item.amount}}
      <button (click)='item.addItem()'>Add</button>
      <button (click)='item.removeItem()'>Remove</button>
    </li>
  </ul>
  `
})
export class MyCart {
  private cartItems: [CartItem] = [];

  public addCartItem() {
    this.cartItems.push(new CartItem('Cart item', 1))
  }

  public cleanCart() {
    this.cartItems = this.cartItems.filter(
      (current, i, array) => current.amount > 0;
    )
  }
}

Check it out in Plunker

答案 1 :(得分:0)

为什么你有3个不同的按钮来增加相同的amount变量?

这些都应该是三个不同的项目吗?

假设您想要3个不同的项目,您可以执行以下操作:

items = ['A', 'B', 'C']

amount = [0, 0, 0]

addItem(index) {
    this.amount[index]++;
}
removeItem(index) {
    this.amount[index]--;
}

HTML:

<div *ngFor="let item of items; let i = index">
    <div (click)="removeItem(i)">-</div> 
    <div>{{amount[i]}}</div> 
    <div (click)="addItem(i)">+</div>
</div>

这应该会给你一个想法。您需要稍微修改一下代码。