我的Angular2代码问题

时间:2016-05-10 15:57:06

标签: javascript angular

1 即可。我在同一页面上有几个按钮,如下所示:

Add button  Add button Add button

2 即可。一旦点击它们就会显示下面的按钮

added

问题:

我有一个包含多个 ADD 按钮的页面,如( 1 ),如果我点击第一个按钮(然后它会显示增加/减少按钮,如( 2 )这是完全正常的)。然后,如果我点击第二个,第三个.... ADD 按钮,(即使我已经递增/递减,递增/递减按钮(2)也会从其他按钮中消失该按钮中的值。)

代码:

HTML

<div *ngFor="#item of list">
  <div *ngIf="currentEl === list">
    <tr>
       <td>
         <input type="button" (click)="dec(elem)" value="Down"/>
         <input type="text" #elem value="0"/>
         <input type="button" (click)="inc(elem)" value="Up"/>
      </td>
    </tr>
   </div>
   </div>
  <div (click)="addTo(list)" *ngIf="currentEl !== list">ADD</div> 

JS:

 let list = ["Banana", "Apple", "Kiwi", "Milk"];


export class App {
     //THIS IS THE ADD BUTTON
       addTo(element){      
          this.currentEl = element;
       }

    inc(elem)
    {
      var nItem = parseInt(elem.value);
      if(nItem < 5)
      {
        nItem +=1;
        elem.value = nItem;
      }
    }

    dec(elem)
    {
      var nItem = parseInt(elem.value);
      if(nItem > 0)
      {
        nItem -=1;
        elem.value = nItem;
      }
    }
  }

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

我假设您正在尝试使用商品实施购物车。请参阅下面的实施。

//our root app component
import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <b>Items:</b>
    <div *ngFor="#item of list">
      <label>{{item.name}}</label>
      <div *ngIf="hasItem(item)">
          <tr>
             <td>
               <input type="button" (click)="dec(item)" value="Down"/>
               <input type="text" [value]="item.total"/>
               <input type="button" (click)="inc(item)" value="Up"/>
            </td>
          </tr>
       </div>
      <button (click)="inc(item)" *ngIf="!hasItem(item)">ADD</button> 
    </div>
    <hr/>
    <div>
    <b>My Cart:</b>
    <div *ngFor="#item of list">
      <label>{{item.name}}</label>: <span>{{item.total}}</span>
    </div>
    </div>
  `,
  directives: []
})
export class App {
   list = [{name: "Banana", total: 0},
            {name: "Apple", total: 0},
            {name: "Kiwi", total: 0},
            {name: "Milk", total: 0}];
   
  //THIS IS THE ADD BUTTON
    inc(item)
    {
      item = this.list.filter(obj => obj.name === item.name);
      var nItem = parseInt(item[0].total);
      if(nItem < 5)
      {
        nItem +=1;
        item[0].total = nItem;
      }
    }

    dec(item)
    {
      item = this.list.filter(obj => obj.name === item.name);
      var nItem = parseInt(item[0].total);
      if(nItem > 0)
      {
        nItem -=1;
        item[0].total = nItem;
      }
    }
    
    hasItem(item) {
      console.log(this.list.filter(obj => obj.name === item.name)[0].total);
      return this.list.filter(obj => obj.name === item.name)[0].total > 0;
    }
    
  constructor() {

  }
}

完整的实现是在Plnkr代码中:https://plnkr.co/edit/2SZCQoyMi5aOZpjYB4sL?p=preview