【发布时间】:2020-05-02 15:02:33
【问题描述】:
我试图在 *ngFor 循环中获取值列表的累积总数,但该值必须返回给父级,然后传递给 for 循环中的下一项,因此父级会知道总也。代码沙箱可以在:https://codesandbox.io/s/angular-test-01-n0hme?fontsize=14&hidenavigation=1&theme=dark
这些值不是在事件上计算的,而是在 ngFor 期间,没有用户交互。
标题“list no {{ count }}”的 ngFor 计数(不使用索引)
ngFor 的累计总数以及 for 循环中的下一项都可以访问此值。
最好的方法是什么?
谢谢
D
文件:app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'test-app';
listNo = 0;
totalPriceOfAllLists: number = 0;
lists = [
{
name: "item list 1",
items: [{ name: "item 1", value: 10 }, { name: "item 2", value: 10 }]
},
{
name: "item list 2",
items: [
{ name: "item 1", value: 10 },
{ name: "item 2", value: 10 },
{ name: "item 3", value: 10 }
]
},
{
name: "item list 3",
items: [
{ name: "item 1", value: 10 },
{ name: "item 2", value: 10 },
{ name: "item 3", value: 10 },
{ name: "item 4", value: 10 }
]
}
];
}
文件:app.component.html
<h2>Test App</h2>
<app-item
*ngFor="let list of lists; let i = index;"
[listIndex]="i"
[list]="list"
></app-item>
<b>Total £ {{totalPriceOfAllLists}}</b>
<hr />
<div class="">
list no 1 cumulativeTotal should be £20<br />
list no 1 cumulativeTotal should be £50<br />
list no 1 cumulativeTotal should be £90<br />
Total should be £160
</div>
文件:item.component.ts
import { Component, OnInit, Input, AfterViewChecked } from "@angular/core";
@Component({
selector: "app-item",
templateUrl: "./item.component.html",
styleUrls: ["./item.component.css"]
})
export class ItemComponent implements OnInit {
@Input() listIndex: number; // shouldn't use index as it should be a counter increment from parent
@Input() list: { name: string; value: number }[];
listNo = 0;
cumaliativeTotal = 0;
constructor() {}
ngOnInit() {
console.log(this.list);
this.getListTotal();
}
ngAfterViewChecked() {}
getListTotal() {
let total: number = 0;
this.list.items.forEach(item => {
total += item.value;
});
this.listTotal = total;
}
}
文件:item.component.html
<div class="item">
<!-- do not use index which is available as i -->
<h4>List no {{ listNo }}</h4>
<div *ngFor="let item of list.items;">
{{ item.name }} - £{{ item.value }}
</div>
<p><b>List total £{{ listTotal }}</b></p>
<p><b>Cumulative total £{{ cumulativeTotal }}</b></p>
</div>
【问题讨论】:
-
链接失效了。
-
我已经在我没有登录的浏览器上测试了链接,并且还启用了 vpn,它工作正常,试试这个链接:codesandbox.io/s/…
-
那是在用户交互上使用 EventEmitter,我想做的是在 for 循环本身,没有用户交互。除非每次运行孩子时我都必须手动推送自定义事件,但是不使用事件发射器不应该有更好/更好的方法吗?输出?也许?
标签: angular