An array variable marked as mat-checked contains the total sum

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>

Answer №1

Give this a shot

calculateTotal():number{ 
let sum = 0;
return this.package.options.filter(option => option['isSelected'] === true)).reduce((sum, x) => sum + (x['cost']*this.numberOfPeople) || 0), 0);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the percentage scores for five different subjects among a class

As a beginner in TypeScript, I am still learning the ropes. Here is the code snippet I used to calculate percentage: pere() { this.E=(((+this.English+ +this.Tamil+ +this.Maths+ +this.Science+ +this.Social)/500)*100); console.log(this.E); The result w ...

Place the label and input elements next to each other within the form-group

My form group includes both a label and an input field <div class="col-md-12 form-group"> <label class="col-sm-2 col-form-label" for="name">Name</label> <input type="text" class="form-control" name="name" id="name" [(ngMode ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

Resizing a column in the Bootstrap CSS grid causes adjacent columns to move

I am currently working with a bootstrap grid that includes an expand component. The issue I am facing is that when I expand one column, the other columns in the same row also shift. Is there a way to make each column independent of the others? expand co ...

Loading custom Angular modules results in an error

Seems like a simple thing, but I'm struggling to figure it out on my own. I have an Angular application with the following key files: app/app.module.ts app/dashboard/dashboard.component.html app/dashboard/stats-tile/stats-tile.component.html I used ...

Guide on breaking a th tag as a line in a table using CSS

I'm attempting to achieve jQuery datatable-style responsiveness in an Angular table child component. I managed to separate the td and th separately using absolute and relative positions but encountered an issue where the th tag is not breaking at the ...

How to troubleshoot Props not functioning in nextjs-typescript?

I'm having trouble with props in my project and I can't seem to figure it out! Here are the three files. I'm still learning typescript but everything seems fine in the code, yet it's not working! Here is index.tsx file: const Home: ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Closing ngx-bootstrap modal post unit tests

After enabling the CSS style in the unit tests of my Angular app, I noticed that every time a component displaying a modal from ngx-bootstrap appears, it remains visible in the browser even after the unit tests for that component have completed running. T ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

The error message "Angular 4 does not recognize the 'dragula' property as a valid property of the 'div' element" is displayed

Struggling to integrate ng2-dragula with the AspNetCore SPA template. Despite trying various solutions, I am still encountering the following error: Exception: Call to Node module failed with error: Error: Template parse errors: Can't bind to 'd ...

Creating a standard arrow function in React using TypeScript: A Step-by-Step Guide

I am currently working on developing a versatile wrapper component for Apollo GraphQL results. The main objective of this wrapper is to wait for the successful completion of the query and then render a component that has been passed as a prop. The componen ...

Having trouble assigning a value of `undefined` to a TextField state in React hook

I am in need of setting the initial state for a TextField date to be undefined until the user makes a selection, and then allowing the user an easy way to reset the date back to undefined. In the code snippet below, the Reset button effectively resets par ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Can the nested package within the package-lock.json file be updated?

Take for instance the make-fetch-happen package within npm/node-gyp/node_modules/ directory. I am looking to update the make-fetch-happen package due to the http-cache-semantics v4.1.0 version being marked as unsafe in this location. Alternatively, is it ...

Having trouble getting Angular's ngClass directive to work correctly when applying multiple conditions

Struggling to make multiple conditions work with [ngClass] Check out a.component.html <div class="version-content" *ngFor="let version of versions; let lastVersion = last" [ngClass]="(version.isComingSoon === true) ? 'dashed': 'solid"> ...

Here is the revised text: "What is the best way to send a variable to a component and retrieve it within the ng-template using

I've developed a component named "foo" that accepts a data object and displays it within an ng-template as its own variable. The issue arises when the variable inside the ng-template is of type any, lacking proper typing for checking and autocomplete ...

Unexpected JSON end causes issue with DELETE request in Next.js version 13

I am currently working on a web app using Next 13 and I have a route.ts file located in the api folder. This file contains two different methods, POST and DELETE. While both methods successfully receive the request, I am facing an issue with JSON parsing ...

What is the method for accessing a validator that has been declared in a reactive form group while within the scope of a custom

Currently, I have a custom component that I am happy with and it is being used in a reactive form as shown below. private init() { const control4 = new FormControl("yy", Validators.pattern(".{2}")); const control5 = new FormControl("zz", Validators.pa ...