angular - 角度插值语法:从所有子对象中计算所有子对象
问题描述
我有以下课程:
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]}
]
}
如何使用插值语法来做到这一点?
解决方案
您应该避免从模板调用方法,因为每次更改检测运行时都会调用该方法。如果值可以更改,您应该使用管道,因为它不会在每次角度变化检测运行时运行,但仅在值更改时运行。
一个以数组(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 }}
推荐阅读
- apache-spark - 如何使用 Pyspark 处理来自 Kafka 的 Debezium 事件?
- php - tinymce 粗体内容显示为纯文本
- angular - Angular 7 和 RxWebValidators 库添加条件验证器将添加按钮设置为禁用
- microsoft-cognitive - 语音服务 Javascript SDK 响应缓慢
- android - Android Studio app.gradle 错误:程序类型已存在:android.support.v4.app.BackStackRecord$Op
- android - 如何禁用列表视图的滚动视图并随着单元格的增加增加列表视图的高度?
- xml - xpath 的命名空间前缀无效
- python - 如何将列从另一个数据框连接到特定列?
- postgresql - 如何在 postgressql 查询中添加 LIMIT 子句?
- laravel - Laravel 5.7 删除没有到达控制器删除方法(返回404错误页面)