单击按钮不更新 angular formControlName 值

Button click not updating the angular formControlName value

我有一个表单,其中包含 +- 用于递增值,并且当我使用这些按钮时 formControlName 不会更新但可以使用当我手动输入时。如何解决这个问题?代码如下:

<form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Amenities</ng-template>
      <h5>How many guests can your place accomodate?</h5>
      <p class="textClass">
        Please specify the nuamber of guests your place can easily accomodate
        comfortably.
      </p>
      <div class="def-number-input number-input safari_only">
        <button
          onclick="this.parentNode.querySelector('input[type=number]').stepDown()"
          class="minus"
        ></button>
        <input
          formControlName = "guestCapacity"
          min="0"
          type="number"
        />
        <button
          onclick="this.parentNode.querySelector('input[type=number]').stepUp()"
          class="plus"
        ></button>
      </div>
</form>

我在控制台记录了该值,还使用了订阅者来查看它是否发生了变化,但正如我之前所说,它仅在我手动输入时有效,而按钮没有任何效果。

submit() {
    console.log(this.secondFormGroup.controls.guestCapacity.value);
  }

嗯,我不确定查询选择器,如果它确实有效,但让我给你一个不同的方法。

如果你想引用 angular 中的节点,你可以使用 #ref,像这样,

<button
  onclick="guestCapacity.stepDown()"
  class="minus"
></button>
<input #guestCapacity
  formControlName = "guestCapacity"
  min="0"
  type="number"
/>
<button
  onclick="guestCapacity.stepUp()"
  class="plus"
></button>

正确的实现方式应该是:

  1. 在输入标签中我们放置了#guestCapacity模板引用变量
  2. 在减号按钮中,我们访问 guestCapacity 表单控件,并将值减 1
  3. 在加号按钮中,我们访问 guestCapacity formcontrol & template 引用变量以将值增加 1。
<form [formGroup]="secondFormGroup">
    <ng-template matStepLabel>Amenities</ng-template>
    <h5>How many guests can your place accomodate?</h5>
    <p class="textClass">
        Please specify the nuamber of guests your place can easily accomodate
        comfortably.
    </p>
    <div class="def-number-input number-input safari_only">

        <!-- Get the guestCapacity formcontrol and decrease the value by 1 -->
        <button (click)="secondFormGroup.get('guestCapacity').setValue(guestCapacity?.value - 1)"
            class="minus"></button>
        <input #guestCapacity formControlName="guestCapacity" min="0" type="number" />

        <!-- Get the guestCapacity formcontrol and increase the value by 1 -->
        <button (click)="secondFormGroup.get('guestCapacity').setValue(guestCapacity?.value + 1)" class="plus"></button>
    </div>
</form>