How can I subtract a value from my array in Angular?

I've been troubleshooting this problem for a while now and I'm hoping that someone here can assist me with finding a solution.

The issue at hand involves an array object containing various values such as id, title, amountCounter. Specifically, the amountCounter is supposed to increment when a button is clicked, but it fails to decrement when the object is removed from the array.

To provide a clearer picture of the problem, I have included a couple of screenshots:

Here is the image after several clicks on ID 1:

And here is the image after clicking "X" to remove the object:

From the images, you can see that the amountCounter in the array increases by 29.99 each time, but does not decrease by 29.99 when the object is removed. I'm struggling to understand why this is happening.

Your help in resolving this issue would be greatly appreciated. Here are the relevant files:

app.component.html

<app-dialog></app-dialog>
<h2>Add values of my service into array:</h2>
<p>Array:</p>
<p>Total: {{amountCounter}}</p>

<div *ngFor="let item of data, let i = index;">
  <span>ID: {{item.id}}</span>
  <span>Title: {{item.title}}</span>
  <span id="remove" (click)="removeElement(i)" class="material-icons">
    Click me to remove and decrement the "amountCounter by 29.99"
  </span>
</div>

app.component.ts

export class AppComponent {
  clickEventsubscription: Subscription;

  ngOnInit() {}

  id: number;
  title: String;
  amountCounter: number;
  isClicked: boolean = false;
  data: any = [];

  constructor(private share: ShareDataService) {
    this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
      this.initialize();
    });
  }

  removeElement(index: number) {
    this.data.splice(index, 1);
  }

  test() {}

  initialize() {
    this.id = this.share.getId();
    this.title = this.share.getTitle();
    this.amountCounter = this.share.getAmountCounter();

    const newData = {
      id: this.id,
      title: this.title,
      amountCounter: this.amountCounter
    };
    this.data.push(newData);
    console.log(this.data);
  }
}

share-data-service.ts

  private subject = new Subject<any>();

  title: String;
  id: number;
  amountCounter: number;

  getId() {
    return this.id;
  }

  getTitle() {
    return this.title;
  }

  getAmountCounter() {
    return this.amountCounter;
  }

  sendClickEvent() {
    this.subject.next();
  }

  getClickEvent(): Observable<any> {
    return this.subject.asObservable();
  }

I've also created a StackBlitz for more insight into the issue:

https://stackblitz.com/edit/angular-ivy-shdyrw?file=src%2Fapp%2Fshare-data.service.ts

Thank you for your assistance.

Answer №1

To implement the solution I proposed earlier, you can follow these steps -->

Modify the following in your code:

In your app.component.ts:

sumOfAmounts(){
    var total = 0;
    this.data.forEach(entry => {
      total += entry.amountCounter
    })
    return total;
  }

In your app.component.html:

<h2>Sum of my service values:</h2>
<p>Array:</p>
<p>Total: {{sumOfAmounts()}}</p>

Also, in your dialog.component.ts:

 updateCounter() {
    this.id = this.id + 1;
    this.amountCounter = this.amount;
    this.share.amountCounter = this.amountCounter;
    this.share.title = this.title;
    this.share.id = this.id;
    this.share.sendUpdateEvent();
  }

Check out the updated code here

Answer №2

Here is a solution you can try:

 updateAmountCounter(index: number) {
    this.total -= 29.99;
    this.items.splice(index, 1);
    this.cartTotal = this.total;
}

If your scenario requires it, consider creating a separate function to calculate the sum of all amount counters in the items array for better organization.

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

Aframe's a-assets feature experiencing issues when loading dynamic data through Angular 2

Since there is no fixed number of assets that need to be loaded from the server, I am utilizing Angular 2 templates to dynamically create assets. Below is a snippet of sample code: <a-assets> <div *ngFor="let scene of floorData.scen ...

Combining multiple forms in Angular 8页面

In my Angular 8 project, I am working on creating a registration/login screen with some animation effects when switching between the two forms. Each form has its own validation rules using form groups. However, I have encountered an issue where the registr ...

What are some methods for integrating a database-driven approach to Angular's internationalization features?

After exploring the Angular i8n guide found here: https://angular.io/guide/i18n, I have gained a good understanding of the concepts. While I appreciate the use of markup and hints in the file, I find it challenging that text resources are confined to a pe ...

Exploring how to traverse a <router-outlet> within its container

I am attempting to switch the active component within a from its parent. After observing how Ionic achieves this, I believe it should resemble the following (simplified): @Component({ template: '<router-outlet></router-outlet>' } ...

Warning issued by npm: An error occurred in the tar file entry due to an invalid argument while trying to

While executing npm ci in my docker container, I encountered the following error: $ npm ci npm WARN tar TAR_ENTRY_ERROR EINVAL: invalid argument, fchown npm WARN tar TAR_ENTRY_ERROR EINVAL: invalid argument, fchown npm WARN tar TAR_ENTRY_ERROR EINVAL: inva ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...

Can a new record be created by adding keys and values to an existing record type while also changing the key names?

If I have the following state type, type State = { currentPartnerId: number; currentTime: string; }; I am looking to create a new type with keys like getCurrentPartnerId and values that are functions returning the corresponding key's value in Sta ...

Is the input URL modified by the Angular HttpClientModule's GET request?

I am currently using an Angular service to make calls to a Node.js server in order to fetch data. Here is a snippet of my code: constructor(private http: HttpClient){ } getPersonData(): Observable<person[]> { //return this.http.get<person ...

Is it possible to deactivate the click event on an Angular mat table row?

Within my Angular mat table, I have implemented code that expands a table row when clicked. However, I now need to prevent certain rows from being clickable based on the "element.disable" property. <ng-container matColumnDef="id"> <th mat-hea ...

Creating a dynamic table with columns of fixed width in Angular on the fly

I am struggling to create a data table with fixed column widths (20% each). I have incorporated div elements in my table structure to enable dynamic row creation using Angular, but this has caused some design issues. My goal is for all rows to occupy 100% ...

Looking to query JSON using jQuery - how can I accomplish this?

Currently, I am utilizing session storage to temporarily store data and attempting to search for a specific string (CatalogNumber) within the session data. If the string is not found, my goal is to add it. Despite my efforts, I have encountered issues wit ...

Checking a String for a Specific Pattern in Angular 6 using Regular Expressions

urn:epc:id:sgln:345344423.1345.143 I need to verify if the string above, entered into a text box, matches the specified format consisting of (urn:epc:id:sgln) followed by numbers separated by two dots. ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...

Make this array output from PHP easier to understand by simplifying it

I'm facing difficulties with the formatting of my JSON data. Here is the structure of my script: $array1 = array(); for($i = 0; $i < 2 ; $i++) { $array1[] = array ( "stocks" => array ( "0" => "apple", "1" => "banana", ...

What is the method for defining a function within a TypeScript namespace?

Suppose there is a namespace specified in the file global.d.ts containing a function like this: declare namespace MY_NAMESPACE { function doSomething(): void } What would be the appropriate way to define and describe this function? ...

extract non-alphanumeric characters from an array of strings using javascript

I am trying to loop over an array of strings in JavaScript and remove special characters from elements that contain them. I have been successful in achieving this with individual strings, but I am facing some challenges when working with arrays of string ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

combine two php arrays that have different lengths by their values

Greetings! I have a query regarding merging two PHP arrays of different lengths based on identical key-value pairs within both arrays. Despite searching through numerous similar posts, none seemed to address my specific requirements. The first array is ge ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...