2017-02-16 58 views
1

我正在嘗試獲取購物車中所有商品的總成本。我能夠獲得每個{{item.rate * item.quantity}}的總計,但我無法找到購物車中所有商品的總和。無法獲得購物車中所有商品的總成本

估計,detail.component.html

<tbody> 
     <tr *ngFor=" let item of Items"> 
      <td> 
      <a cart-button [item]="item" action="remove" class="btn btn-default btn-sm"> 
       X 
      </a> 
      </td> 
      <td>{{item.itemName}}</td> 
      <td>{{item.rate}}</td> 
      <td> 

      <custom-counter [(counter)]="item.quantity"></custom-counter> 

      </td> 
      <td>${{item.rate*item.quantity | number: '.2'}}</td> 
     </tr> 
     </tbody> 
     <tfoot> 
     <tr> 
      <td colSpan="4" class="text-right">Total</td> 
      <td>${{ Items | cartTotal | number: '.2'}}</td> 
     </tr> 
     </tfoot> 

totalPipe.ts

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({name: 'cartTotal'}) 
export class TotalPipe implements PipeTransform { 

transform(value) { 
     console.log("here"); 
    let total = 0; 
    if (value) { 
     value.forEach(item => { 
      total += item.quantity * item.rate; 
     }); 
    } 
    return total; 
} 
} 

我可以打電話給管,但它並沒有全部更新。

counter.component.ts

@Component({ 
    selector: 'custom-counter', 
    template: ` 
    <button (click)="decrement()">-</button> 
    <span>{{counter}}</span> 
    <button (click)="increment()">+</button> 
    ` 
}) 
export class CustomCounterComponent { 
counterValue = 0; 
    @Output() counterChange = new EventEmitter(); 

    @Input() 
    get counter() { 
    return this.counterValue; 
    } 

    set counter(val) { 
    this.counterValue = val; 
    this.counterChange.emit(this.counterValue); 
    } 

    decrement() { 
    this.counter--; 
    } 

    increment() { 
    this.counter++; 
    } 
} 
+0

請提供plunker。 –

+0

糾正我,如果我錯了,但'total'必須是'this.total',對不對?就像:'this.total + = item.quantity * item.rate;'和'return this.total;' – mickdev

+0

你好,我不知道如何創建一個plunker。這些項目是通過api生成的。 –

回答

1

*ngFor=" let item of Items"是資本i個項目。

${{ items | cartTotal | number: '.2'}}是小寫字母i。

因此,將items更改爲Items,或者將組件中的屬性更改爲items,它應該可以工作。

+0

感謝我們正在朝着正確的方向前進......唯一的問題是我想總結'生成的數量。 ,它使用Items對象中設置的初始值。我將更新代碼以顯示自定義計數器。 –

相關問題