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:

https://i.sstatic.net/bMmOr.png

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

https://i.sstatic.net/bjyp0.png

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

What is the best way to access elements and attributes from a specific JSON file?

Is there a way to access each property within the JSON data provided? Additionally, I am interested in filtering specific objects based on their IDs. How can this be achieved using the array.filter method in JavaScript? { "records": [ ...

Fixing prop passing issues in Vue.js components to prevent errors

My Vue-cli install with TypeScript is set up to render JSX using a boilerplate. However, I am facing an issue when trying to pass a property to the HelloWorld component. Here's what my code looks like: export default Vue.extend({ name: 'App&apo ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...

Incorporate Angular Material into a personalized library

In my quest to create a reusable library for various projects, I decided to embark on building my own from scratch. The process began with the formation of a new application solely dedicated to housing this library: ng new lib-collection cd lib-collection ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Bidirectional data binding in Angular 2 allows for communication between parent components and directives

Update: Experimenting with Angular2 Beta, I am working on incorporating an "editor" component template that includes a directive wrapping the Ace editor. In this scenario, the "editor" component acts as the parent of the Ace wrapper directive, and my goal ...

What is the correct method for compiling a list of users?

Hello, I have developed a basic user list based on database results, but I am facing two issues with it. Currently, my list displays like this: [UserOne, ...][UserTwo, ...] However, I need the format to be: [UserOne],[UserTwo]... The three dots repres ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Customizing URL addresses based on webpack build configuration

Is there a way to parametrize the URL based on the webpack build profile? I'm referring to the URL used for services to fetch data from an API. For instance, in my Angular2 app: excerpt from package.json: "scripts": { "build-prod": "rimr ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

Is it possible for React props to include bespoke classes?

In our code, we have a TypeScript class that handles a variety of parameters including type, default/min/max values, and descriptions. This class is utilized in multiple parts of our application. As we switch to using React for our GUI development, one of ...

The ability of Angular 4 ngComponentOutlet to load dynamic components is great, however, there seems to be an issue

Currently, I am faced with the challenge of loading various 'parent' components and injecting route content into these individual parent components by utilizing ng-content in each one. Essentially, the purpose of each parent component is to manag ...

Accessing the access token in your Angular application right after the login process with Auth0

I've been working on integrating auth0-spa-js in my Angular application, and I'm encountering an issue extracting the access token after a successful user authentication. Despite reading multiple articles on the topic, I'm still unclear on h ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...

Exploring the power of Angular Module Federation in leveraging remote services

I am breaking down an Angular application into multiple microfrontends. One of these microfrontends manages the shopping cart, and it includes a service for storing added products. The main shell microfrontend needs to access this service to display the nu ...