Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在角度表中显示每个父项的子项总和_Angular - Fatal编程技术网

Angular 在角度表中显示每个父项的子项总和

Angular 在角度表中显示每个父项的子项总和,angular,Angular,我想计算一个角度(6)表中每行的childs总数。一道菜的配料是有价格的。我想把每道菜的价格加起来 角度表仅显示所有父对象的第一个父对象的总和。我猜是因为返回总计。 当我删除return total时,console.log会显示每个父级的正确输出。 当我把“返回总数”放在下面的一个括号中时,它只显示最后一位家长的总数 如何确保Angular为每个父级提供输出?(因此,继续循环并每行打印正确的输出)?提前谢谢 calcPrice() { for (let dish of this.d

我想计算一个角度(6)表中每行的childs总数。一道菜的配料是有价格的。我想把每道菜的价格加起来

角度表仅显示所有父对象的第一个父对象的总和。我猜是因为返回总计。 当我删除return total时,console.log会显示每个父级的正确输出。 当我把“返回总数”放在下面的一个括号中时,它只显示最后一位家长的总数

如何确保Angular为每个父级提供输出?(因此,继续循环并每行打印正确的输出)?提前谢谢

 calcPrice() {

    for (let dish of this.dishes) {

      let total = 0;

      for (let ingredient of dish.ingredients) {
        total += ingredient.pricePerUnit;

      }
      return total;
    }
  }
html:


{{calcPrice()}}

您可以将一行程序用于
reduce

JS中的示例:

常数盘=[
{名称:'鸡肉帕尔姆',成分:[
{名称:'酱油',价格:2,金额:200},
{名称:'Chiken',价格:5,金额:150},
{名称:'Parmigiano Regiano',价格:8,金额:50},
{名称:'橄榄油',价格:1.5,金额:10},
]}
];
功能价格(碟){
返回菜。配料。减少((p,n)=>p+n.price,0);
}

log(`Expected:2+5+8+1.5=${2+5+8+1.5},得到${dishPrice(dishs[0])}`)
calcPrice
中删除
for
循环,并使用
{{calcPrice(dish)}}
传入
dish
,谢谢,我会尝试一下。但是calcPrice的代码会是什么呢?我之前确实提供了一个答案,但是有人指出,从模板调用函数是非常低效的。最好是在盘子中循环,并为每个盘子添加一个
total
属性。很好,这很有效。同样感谢您对reduce的解释!
<tr *ngFor='let dish of dishes'>
  <td>{{ calcPrice() }}</td>