【问题标题】:Reduce Function in Angular Template减少 Angular 模板中的函数
【发布时间】:2022-07-20 21:55:40
【问题描述】:

是否可以在 Angular 的 HTML 中做一个 reduce 函数? 我在下面做了这个,但它输出解析错误。

HTML

<div *ngIf="report$ | async as report">
  <p>
    {{ report?.payrolls?.reduce((prev, curr) => (prev.gross - prev.c_a - prev.statutory = prev.charges) + (curr.gross - curr.c_a - curr.statutory = curr.charges), 0) | number }}
  </p>
</div>

TS

@Select(ReportState.getEmployeePayslip) report$: Observable<EmployeePayslip>;

【问题讨论】:

  • 为什么会有人反对这个?这个问题很清楚
  • 很可能是因为最好在 ts 代码或专用管道中进行这些计算。
  • 避免在模板中调用函数,你会因为变化检测而遇到性能问题

标签: angular angular-template ngxs


【解决方案1】:

不,模板中的功能不起作用。

我推荐2个选项:

1.创建第二个 observable,它依赖于第一个,也可以通过模板中的async 管道访问。

this.payrollSummary$: Observable<number> = this.report$.pipe(
  map(report => report?.payrolls?.reduce(/*...*/)),
);

2。使用自定义模板管道传递值

<p>{{ report | payrollSummary }}</p>

@Pipe({
  name: 'payrollSummary',
})
export class PayrollSummaryPipe implements PipeTransform {
  transform(report: EmployeePayslip): number {
    return report?.payrolls?.reduce(/*...*/);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多