2017-02-16 57 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对象中设置的初始值。我将更新代码以显示自定义计数器。 –

相关问题