我正在使用mat-checked来从数组中获取总和。在这种情况下,如果数组中的项目数为4,则一切正常。但是问题是数量是可变的,所以我得到一个错误:
错误TypeError:无法读取未定义的属性'isChecked'
如何使总和始终独立于数组中的项数工作?
所以我的代码是这样的:
component.ts
get total(): number {
return (this.paquete.extras2[0].isChecked ? this.paquete.extras2[0].costo : 0) * this.numeroPersonas +
(this.paquete.extras2[1].isChecked ? this.paquete.extras2[1].costo : 0) * this.numeroPersonas +
(this.paquete.extras2[2].isChecked ? this.paquete.extras2[2].costo : 0) * this.numeroPersonas +
(this.paquete.extras2[3].isChecked ? this.paquete.extras2[3].costo : 0) * this.numeroPersonas +
this.subtotal;
}
component.html
<div *ngFor="let extra of paquete.extras2">
<div class="d-flex justify-content-between" [ngClass]="{ 'textExtra': !extra.isChecked}">
<mat-checkbox class="nmb" [(ngModel)]="extra.isChecked">
<span>
{{extra.nombre}}: {{ extra.costo | currency: '$ ' : 'symbol' : '1.0' }}/persona x {{numeroPersonas}}
</span>
</mat-checkbox>
<span class="myWhiteSpace ml-4 ">{{ extra.costo * numeroPersonas | currency: '$ ' : 'symbol' : '1.0' }}</span>
</div>
<hr class="my-2">
</div>
<span>{{total | currency: '$ ' : 'symbol' : '1.0' }}</span>
答案 0 :(得分:1)
尝试一下
get total():number{
let sum =0;
return this.paquete.extras2.filter(e=>e['isChecked'] ===true)).reduce((sum, x) => sum +(x['costo']*this.numeroPersonas) || 0), 0);