Currently, I am utilizing mat-checked to calculate a total sum from an Array. The issue arises when the number of items in my array varies, triggering an error:
ERROR TypeError: Cannot read property 'isChecked' of undefined
Is there a way to ensure that the sum calculation always functions correctly, regardless of the number of items in the Array?
The code snippet in question is as follows:
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>