我试图显示数组中每组项目的小计。我能够显示列表并计算组件中的运行总计,但是不会显示该值。
我使用trackBy来启动计算(也许有更好的方法)。我尝试使用ngDoCheck和ngAfterContentChecked来更新视图。将显示要显示的值,但是我无法在模板中反映出来。
这是代码示例。
<ul>
<li *ngFor="let invoice of sortedList">
<span>{{invoice.key}}</span>
<ul>
<li *ngFor="let item of invoice.value; trackBy: sumAmounts;">
<span class="row">{{item.DATE | date: "d/M/y"}}</span>
<span class="row">{{item.INVOICE}}</span>
<span class="row">{{item.AMOUNT | currency: 'USD':'symbol-narrow'}}</span>
<span class="row">{{item.TAX}}</span>
<span class="row">{{item.DU_DATE | date: "d/M/y"}}</span>
<span class="row">;{{item.DAYS}}</span>
</li>
<div class="line"</div>
<div>
<span>Totals:</span>
<span>{{runningTot | currency: 'USD':'symbol-narrow'}}</span>
</div>
</ul>
</li>
</ul>
` 在组件中
sumAmounts(index, rec) {
if (rec.CODE != this.cusId) {
this.runningTot = rec.AMOUNT;
this.cusId = rec.CODE;
console.log('initialized value: ', this.runningTot);
this.summ = true; // not relevant
this.counter++; // used to trigger ngDoCheck
}
else {
this.runningTot = this.runningTot + rec.AMOUNT;
console.log('Addition ', this.runningTot);
}
}
每当检测到新的客户ID时,我都希望在模板中显示runningTot。即使变量“ runningTot”具有值,模板中的值仍为0。
DoCheck功能如下所示:
ngDoCheck() {
if (this.counter != this.prv_Counter) {
this.prv_counter = this.counter;
}
console.log('do check');
}
答案 0 :(得分:0)
我认为您应该删除trackBy
并仅编写如下代码:
// component.ts
get runningTot() {
// loop through your array and return the sum
}
顺便说一句,this.counter++; // used to trigger ngDoCheck
对我来说似乎是一个大危险信号,因为您依靠奇怪的副作用来重新呈现视图
答案 1 :(得分:0)
您可以创建类似
的管道import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'totalCount'
})
export class TotalCountPipe implements PipeTransform {
transform(value: any[], args?: any): any {
return value.map(v => v.AMOUNT).reduce((accumulator, currentValue) => accumulator + currentValue);
}
}
请在模块中注册管道,例如:
@NgModule({
...
declarations: [
...
TotalCountPipe
],
...
})
在模板中,您可以使用:
...
<div>
<span>Totals:</span>
<span>{{invoice.value| totalCount | currency: 'USD':'symbol-narrow'}}</span>
</div>
...