Steps for creating a button that increments by using ng loop:1. Begin

I am attempting to create a button that can be used to increment and decrement. However, I am facing an issue where all input fields are being affected instead of just one.

This is the code in body.component.html

<div class="items-detail-detail" *ngFor="let detail of card.detail">
<div class="items-detail-information3">
  <div class="btn-block" >
    <button class="btn btn-default" (click)="onDecrement()">
      <i class="material-icons">remove</i>
    </button>
  </div>
  <div class="input-group" >
    <input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
  </div>
  <div class="btn-block">
    <button class="btn btn-default" (click)="onIncrement()">
      <i class="material-icons">add</i>
    </button>
  </div>

</div>

This is the code in body.component.ts

export class BodyComponent implements OnInit {
  private counter : number = 0; 
    onIncrement() {
      this.counter++
  } 
    onDecrement() {
      this.counter--
  } 
ngOnInit() {
}}

The current behavior of the code is shown in the image below:

enter image description here

When clicking the [+] button at the top, it increments all input fields as shown here:

enter image description here

Apologies for any language barriers, thank you for your assistance.

Appreciate it!

Answer №1

It is essential to keep track of the counter variable for all the cards.

inside body.component.html

<div class="items-detail-detail" *ngFor="let detail of card.detail">
<div class="items-detail-information3">
  <div class="btn-block" >
    <button class="btn btn-default" (click)="onDecrement(detail)">
      <i class="material-icons">remove</i>
    </button>
  </div>
  <div class="input-group" >
    <input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
  </div>
  <div class="btn-block">
    <button class="btn btn-default" (click)="onIncrement(detail)">
      <i class="material-icons">add</i>
    </button>
  </div>

</div>

within body.component.ts

export class BodyComponent implements OnInit {
    private counter: number = 0;
    onIncrement(item) {
        item.counter = item.counter ? item.counter + 1 : 1;
    }
    onDecrement(item) {
        item.counter = item.counter ? item.counter - 1 : 0;
    }
    ngOnInit() {}
}

Answer №2

Your current issue arises from using the same counter for all card details on your site.

<div class="input-group" >
    <input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
  </div>

To resolve this, consider assigning unique counter values to each individual card for accurate updates.

Answer №3

@Hey there, make sure your detail is defined as a property "counter" so that you can increment this property specifically, instead of a global one.

<div class="items-detail-detail" *ngFor="let detail of card.detail">
   ...
    <!--Remember to pass "detail" as an argument in the button-->
    <button class="btn btn-default" (click)="onDecrement(detail)">
    ...
    <!--Ensure you access detail.counter for the value input field-->
    <input type="number" value="{{detail.counter}}" class="form-control" style="text-align:center;" >
    ...
    <!--Similarly, use onIncrement with detail.counter--->
     <button class="btn btn-default" (click)="onIncrement(detail)">
...
</div>

   //private counter : number = 0;  <--Avoid using a "global" variable
    onIncrement(detail:any) {
      detail.counter++  //<--increment "detail.counter"
  } 
    onDecrement(detail:any) {
      detail.counter-- //<--decrement "detail.counter"
  } 

You can simplify the code even further by using:

<button class="btn btn-default" (click)="detail.counter++">
<input type="number" value="{{detail.counter}}">
<button class="btn btn-default" (click)="detail.counter--">

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

Utilizing ngFor to generate buttons that are disabled based on specific conditions

I need assistance with creating a dynamic list of buttons from an array using ngFor. While I have achieved this, my current issue lies in disabling the buttons once they exceed a certain "number" representing the user's level. Here is an example of w ...

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

Error: Mongoose Schema Undefined when Route is Added in Separate File

For the sake of organizing my code, I made the decision to separate all of my schemas and routes into different files within my directory, and then required them in my app.js. Each schema corresponds with each route. This method has worked for all but one ...

Error: The function user.comparePassword does not exist or is not defined

I am facing an error that says TypeError: user.comparePassword is not a function. I have ensured that all dependencies are installed and the APP is linked to all the libraries. I tried using Postman to retrieve data, but it doesn't seem to be workin ...

Delay in Response of OnTextChanged Event in ASP.NET

The functionality is there, but it doesn't respond immediately. It only works when I click on something. I attempted using the onkeyPress method as well: <asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress" ></asp:TextBox& ...

Configuring a custom domain for a Rust service on Clever Cloud: A step-by-step guide

After successfully deploying my Rust service to the Clever Cloud platform and testing it on PROD and localhost, I am now facing the challenge of binding my custom domain with the deployed service. I would like to eliminate the need for using the lengthy C ...

Display MySQL data in a Jade/Pug view by separating it into different sections

Here is the code that generates a list of addresses from the database in the format "123 Hollywood Ave., Los Angeles, California". However, I only want to display 123 Hollywood Ave. I attempted splitting up the address using the split(',') method ...

Swapping out a sequence of characters in a web address with a different set

Swapping out imgur for filmot, Enter URL - https://i.stack.imgur.com/Uguvn.jpg Click the submit button After clicking submit, a new tab should open with the link .filmot.com/abcde.jpg. <html> <head> <title>input</title> <sc ...

Access the Vue instance from a different element instance

I've developed a leaflet map using vue.js. There's a method I've created called 'showSubmit' that needs to be triggered on the leaflet marker moveend event. Here's what I'm currently doing: this.map.markers.user.on("move ...

What steps do I need to take in order to ensure that each webpage displays unique thumbnails?

As a newcomer to website development, I recently looked into implementing open graph on my site. However, I ran into an issue where I could only set one thumbnail for the entire website. This posed a problem as I wanted each navigation menu tab (Home, Abou ...

Is there a way to dynamically insert the value of an input field into a text field in real time using Javascript or ajax?

In my form, there is a text field with the id #image_tag_list_tokens. It looks like this: = f.text_area :tag_list_tokens, label: "Tags (optional) ->", data: {load: @image_tags }, label: "Tags" Additionally, I have an input field and a button: <i ...

Adjust the canvas size to perfectly fit within the parent bootstrap cell in a grid layout

I am currently in the process of creating a dashboard using the Bootstrap grid. Some of the cells contain a canvas element, and I am trying to ensure that it matches the size of its parent. My approach involves the following calculations: var parent = can ...

What is the best way to add a separator in a b-dropdown menu once the options have been loaded using Vue?

Here is the code snippet for my dropdown element: <b-dropdown id="SchemaDropdown" name="SchemaDropdown" variant="form-control" class="" style="width: 100%" ...

Validation error detected in the textbox fields

I have incorporated Bootstrap into my application. For a specific functionality, I am dynamically creating dropdown and textbox controls based on a count and implementing validation. However, the validation seems to be malfunctioning only for the textbox ...

CSS Style in Safari does not conceal Div on Tailwind

When switching the screen from desktop to mobile in ReactJS/Tailwind, I have hidden certain images using the following code: <div className="flex shrink flex-row justify-between w-[60%] h-[25%] sm:w-[95%] sm:h-[52%] mb-[-10px] mt-[-15px] lg:mt-0&qu ...

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Having trouble retrieving text using getText() or getAttribute("innerHTML")

getAttribute but struggling to retrieve the text associated with each combobox. I need to access the text content of every combobox. <small> <input type="checkbox" checked="checked" value="on" name="irOperations[0]"/> Account Activity < ...

Issue with intrinsic attributes detected in Typescript for the component

Hey, I'm encountering an issue that says, "The type '{ data: dataProp[]; }' cannot be assigned to type 'IntrinsicAttributes & dataProp'. A property 'data' does not exist on type 'IntrinsicAttributes & dataPro ...

Navigate to a specific element using Selenium WebDriver in Java

Currently, I am utilizing Selenium along with Java and ChromeDriver to execute a few scripts on a website. My goal is to scroll the driver or the page to a specific element positioned on the webpage. It is important that this element is visible. I am awa ...

Building a dynamic Single Page Application with the power of Durandal

Our vision for the single-page app is to create a dynamic system where users can personalize their views and widgets in real-time. Instead of predefined views and viewmodels on the server, we want end-users to have the flexibility to define and customize w ...