【发布时间】:2018-07-29 19:05:57
【问题描述】:
我的 json 文件中有 5 个人的数组。每个人都有一个包含项目的数组。 在我的 html 代码中,我使用 *ngFor 循环显示他们的名字。我还想显示物品价格的总和。 为了一起计算他们商品的价格,我在我的 TypeScript 代码中使用了一个函数。我正在控制台中显示总价格。
问题是,我在打字稿文件中使用的当前代码再次循环遍历这些人。所以我用 *ngFor 循环遍历我的 html 中的人员,在此我调用函数 getTotal(),它再次循环遍历人员 。当然,我只想循环一次。
json
"persons":[
{
"name": "Peter",
"items": [
{
"name": "pen",
"price": 1.50
},
{
"name": "paper",
"price": 2.00
}
]
},
{
"name": "Maria",
"items": [
{
"name": "scissors",
"price": 4.00
},
{
"name": "stickers",
"price": 3.00
}
]
}
// three more persons
]
html
<div *ngFor="let person of persons"> <!--here I'm looping through the persons-->
<p>{{person.name}}</p>
<p>Total <span>{{getTotal()}}</span></p> <!--here I'm calling the function, which will loop through persons again-->
</div>
打字稿
getTotal() {
for(let person of this.persons){ //here I'm looping through the persons again (what I actually don't want)
let total = 0;
for(let item of person.items){
total = total + item.price;
}
console.log(total);
}
}
现在我的问题是: 如您所见,我在我的 html 代码中使用 *ngFor 和在 getTotal() 中的 typescript 代码中循环访问人员。我这样做只是为了在以下循环中访问他们的项目 (person.items)。我想摆脱第一个循环并使用 *ngFor 访问我正在循环的当前元素。我怎样才能做到这一点,甚至有可能吗?
【问题讨论】:
-
我会在显示之前在组件中进行计算,主要是因为在模板中调用方法通常是一个坏主意,因为它在每次更改检测时都会调用。
-
请检查更新的答案,正如@Alex刚刚在评论中所说的那样实施
标签: json angular loops typescript ngfor