我该如何实现dish.dishCost的总和? 听起来很简单,但我仍然遇到问题,在我的basket.component.html ...中尝试了许多不同的操作。
basket.component.html:
<tbody *ngFor='let dish of dishesInBasket'>
<tr>
<td data-th="Product" >
<div class="row" >
<!-- <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive" /></div> -->
<div class="col-sm-10">
<h4 class="nomargin" >{{dish.dishName}}</h4>
<p>{{dish.dishDescription}}</p>
</div>
</div>
</td>
<td data-th="Price">{{dish.dishPrice}} €</td>
<!-- <td data-th="Quantity">
<input type="number" class="form-control text-center" value="1">
</td> -->
<!-- <td data-th="Subtotal" class="text-center">1.99</td> -->
<!-- <td class="actions" data-th="">
<button class="btn btn-info btn-sm"><i class="fa fa-refresh"></i></button>
<button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
</td> -->
</tr>
</tbody>
<tfoot *ngFor='let dish of dishesInBasket'>
<tr class="visible-xs">
<td class="text-center"><strong>Total 1.99</strong></td>
在最后一行中,我需要dish.dishCost的总和。 html中的* ng ***是否有可能,还是我必须在.ts文件中实现它?
我也没有在.ts文件中找到解决方案:(
basket.component.ts:
import { BasketService } from './basket.service';
import { Component, OnInit } from '@angular/core';
import { ShoppingCartModule } from 'ng-shopping-cart';
import { Dish } from '../dishes/dishes';
@Component({
selector: 'app-basket',
templateUrl: './basket.component.html',
styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {
constructor(private basketService: BasketService) { }
dishesInBasket: Dish[] = [];
ngOnInit() {
this.basketService.getDishesFromBasket().subscribe(
dishes => this.dishesInBasket = dishes);
}
}
提前谢谢!
答案 0 :(得分:0)
在您的.ts文件中:
export class BasketComponent implements OnInit {
dishSum = 0;
constructor(private basketService: BasketService) { }
dishesInBasket: Dish[] = [];
ngOnInit() {
this.basketService.getDishesFromBasket().subscribe(
dishes => {
this.dishesInBasket = dishes;
this.dishesInBasket.forEach(item => {
this.dishSum += item.dishCost;
});
console.log(this.dishSum);
});
}
}
在您的html模板中:
<strong *ngIf="dishSum!==0">Total {{dishSum}}</strong>