【问题标题】:Button click not updating the angular formControlName value按钮单击不更新角度 formControlName 值
【发布时间】:2020-04-14 11:40:23
【问题描述】:

我有一个表单,其中有 +- 用于递增值,并且当我使用这些按钮时 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 typescript formgroups


    【解决方案1】:

    正确的实现方式应该是:

    1. 在输入标签中我们放置了#guestCapacity模板引用变量
    2. 在减号按钮中,我们访问guestCapacity表单控件,并将值减1
    3. 在加号按钮中,我们访问guestCapacity formcontrol & 模板引用变量以将值增加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>
    

    【讨论】:

      【解决方案2】:

      好吧,我不确定查询选择器是否真的有效,但让我给你一个不同的方法。

      如果你想以角度引用一个节点,你可以使用#ref,像这样,

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

      【讨论】:

      • 我试过了,但没有按照我想要的方式工作。
      猜你喜欢
      • 2015-12-03
      • 2017-07-22
      • 1970-01-01
      • 2016-11-24
      • 2020-03-13
      • 1970-01-01
      • 2019-03-28
      • 2017-12-14
      • 2021-12-21
      相关资源
      最近更新 更多