通过单击单独的按钮增加表单控件的值

问题描述 投票:1回答:1

我试图通过单击两个单独的按钮来增加或减少表单控制值。但是以某种方式未检测到更改,并且每次单击增加或减少按钮时,我都会得到相同的旧值。

输入类型是数字,我试图通过CSS隐藏默认的增减按钮,而我的自定义按钮将管理这些部分。由于我刚接触过角度游戏,所以我不太了解自己在犯什么错误。

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


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


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

decreament(){
  this.settingForm.get('capacity').value -1;
}
angular typescript angular-forms
1个回答
1
投票

这是您当前尝试的问题:

  1. 一旦增加容量],您就不会保存这些值
  2. 在模板中,增量以-表示,反之亦然
  3. 。ts

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

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

。html

<form [formGroup]="settingForm">
    <input type="number" formControlName="capacity">
    <button (click)="increament()">+</button>
    <button (click)="decreament()">-</button>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.