Search code examples
angulartypescriptangular-forms

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;
}

Solution

  • 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>