2017-02-14 52 views
1

在我Angular2程序,我已經得到了'視圖'下面的代碼:事件觸發的多個元素,而不是一個在* ngFor

<ul class="cart"> 
    <li *ngFor="let item of cartService.cart$ | async">//BehaviorSubject 
     <h3 class="title">{{item.title}}</h3> 
     <span class="descr">{{item.description}}</span> 

     <button (click)="decrQnt()">-</button> 

      <form action="#"> 
      <input type="text" maxlength="3" id="qnt" readonly="readonly" value="{{qnt}}"> 
      </form> 

      <button (click)="incrQnt()">+</button> 
    </li> 
</ul> 

component.ts

public qnt: number = 1; 

incrQnt(){ 
    this.qnt < 100 ? ++this.qnt : 0; 
} 

decrQnt(){ 
    this.qnt > 1 ? this.qnt-- : 0; 
} 

問題是,我的功能同時爲我的視圖中的所有元素工作* ngFor我當然需要增加/減少數量只有一個元素點擊哪個按鈕。

我試圖通過「項目」作爲參數來觸發功能,但然後我不得不屬性「項目」上型AppComponent不存在

在視圖試圖改變{{QNT}}到{{item.qnt}},並獲得無法讀取的不確定

財產QNT我想這是因爲使用BehaviorSubject的,因爲item.description和item.title其他性能如通過JSON傳遞,而qnt在運行時被初始化。

但是現在該如何處理呢?

回答

1

我希望每個項目AHS自己的qnt財產 你遞增/遞減功能也可以通過在你想要的操作中的各個item

<button (click)="decrQnt(item)">-</button> 
<button (click)="incrQnt(item)">+</button> 


incrQnt(item){ 
    item.qnt < 100 ? ++item.qnt : 0; 
} 

decrQnt(item){ 
    item.qnt > 1 ? item.qnt-- : 0; 
} 
+0

也沒什麼改變,什麼也沒有顯示在控制檯中。我只是把那裏的console.log函數來測試行爲,它的工作原理,但增量/減量函數既不工作也不會在控制檯中調用任何錯誤。 –

+0

我不得不在我的json對象中添加屬性qnt(我想在開始的時候添加它),並且所有的東西都沒問題 –

相關問題