首页 > 解决方案 > 角度插值语法:从所有子对象中计算所有子对象

问题描述

我有以下课程:

export class VrpInstance {
  routes: Array<Route>;
}

export class Route {
  points: Array<number>;
}

在 HTML 文件中,我有一个对象列表VrpInstance,对于每个对象,我想使用插值语法显示其所有路线的点总数。

我尝试使用: {{[].concat.apply([], vrpInstance.routes).length}}vrpInstance.routes.flat()它们都没有按预期工作。

期望的行为: 对于一个vrpInstance看起来像下面的对象,我想输出长度 6(因为我总共有 6 个点:[1、2、3、4、5、6])。

{
 "routes" : 
  [ 
    { "points" : [1, 2, 3]},
    { "points" : [4, 5, 6]} 
  ]
}

如何使用插值语法来做到这一点?

标签: angulartypescript

解决方案


您应该避免从模板调用方法,因为每次更改检测运行时都会调用该方法。如果值可以更改,您应该使用管道,因为它不会在每次角度变化检测运行时运行,但仅在值更改时运行。

一个以数组(VrpInstance)为参数的简单管道:

@Pipe({name: 'calculatePoint'})
export class CalculatePointPipe implements PipeTransform {
  transform(route: VrpInstance): number {
    const total = 0;
    route.routes.forEach((points: Array<number>) => {
        total += point.length;
    })
    return total;
  }
}

然后在 HTML 中:

{{ routes | calculatePoint }}

推荐阅读