Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment form control Value by clicking a separate button

I am trying to increase or decrease a form control value by clicking on two separate buttons. But somehow the changes are not detecting and i am getting same old value every time when clicking the increase or decrease button.

The input type is number and I am trying to hide the default increment and decrement button by CSS and my custom buttons will manage those parts. As I am new to angular so I don't have much idea what is the mistake I am making.

<div>
  <input type="number" formControlName="capacity">
  <button (click)="increment()">-</button>
  <button (click)="decrement()">+</button>
</div>


ngOnInit() {
    this.settingForm = this.fb.group({
      capacity: new FormControl(1, [
        Validators.required,
        Validators.min(1),
        Validators.max(5)
      ])
    })
  }


increment(){
  this.settingForm.get('capacity').value +1;
}

decrement(){
  this.settingForm.get('capacity').value -1;
}
like image 900
Swagata Adhikary Avatar asked Feb 06 '26 20:02

Swagata Adhikary


1 Answers

Here are the issues with your current attempt:

  1. You aren't saving the values once you increment capacity
  2. In the template increment was denoted as - and vice versa for decrement

.ts

increment() {
  this.settingForm.setValue({
    capacity: this.settingForm.get("capacity").value + 1
  });
}

decrement() {
  this.settingForm.setValue({
    capacity: this.settingForm.get("capacity").value - 1
  });
}

.html

<form [formGroup]="settingForm">
    <input type="number" formControlName="capacity">
    <button (click)="increment()">+</button>
    <button (click)="decrement()">-</button>
</form>
like image 182
Nicholas Kurian Avatar answered Feb 09 '26 12:02

Nicholas Kurian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!