【问题标题】:Angular Reactive Form control with type=number will re-render on blurtype=number 的 Angular Reactive Form 控件将在模糊时重新渲染
【发布时间】:2019-02-04 12:08:27
【问题描述】:

我有一个 Angular(v7) 响应式表单(可能与纯模板表单相同)。 带有type="number"<input> 将重新渲染并运行模糊验证。
<input> 旁边的错误反馈<div> 中有一个值建议按钮,单击该按钮将使用建议值(由异步验证器提供)填充输入。
但是,如果您第一次单击该按钮,<input> 的模糊会触发整个元素的重新渲染,因此对输入没有影响。您必须再次单击该按钮才能使其工作。

我没有找到任何禁用此重新渲染行为的选项。

演示:stackblitz.com

.ts 文件:

ngOnInit(): void {
    this.newPlanForm = this.formBuilder.group({
      plan_id: [
        {
          value: this.plan.plan_id,
          disabled: !this.plan.insurer_id,
        }, {
          validators: [Validators.required, this.planIdSyntaxValidator.bind(this)],
          asyncValidators: this.planIdDuplicationValidator.bind(this),
          // updateOn: 'blur' // this is my hacky solution. The original problem occours without it
        }
      ],
      ...
    });
}

planIdDuplicationValidator(control: AbstractControl): Observable<ValidationErrors | null> {
    // duplication check
    ...
}

fillInSuggestedPlanId(): void {
    this.form.plan_id.setValue(this.form.plan_id.errors.duplicatePlanId);
}

// convenience getter for easy access to form fields
get form() {
    return this.newPlanForm.controls;
}

HTML:

<form [formGroup]="newPlanForm">
    ...
    <label for="plan_id">Plan ID<sup>*</sup></label>
    <input type="number" class="form-control" id="plan_id" name="plan_id"
           [ngClass]="{ 'is-invalid': form.plan_id.errors }"
           formControlName="plan_id"/>
    <div class="invalid-feedback" *ngIf="form.plan_id.dirty && form.plan_id.errors">
      <p *ngIf="form.plan_id.errors.duplicatePlanId">
        This plan ID is already taken. Next available is
        <a (click)="fillInSuggestedPlanId()" class="btn-link">
          {{suggestedPlanID}}
        </a>
      </p>
    </div>
    ...
</form>

【问题讨论】:

  • 尝试从验证器数组中删除 updateOn:'blur' 属性
  • @Chellappan 抱歉,这是我的 hacky 解决方案,实际上没有它就会出现问题。 (顺便说一句,它是控件本身的配置属性,而不是验证器级别。)请参阅我的编辑。
  • 请创建一个演示来显示这个问题:)
  • @AJT_82 添加了演示。请输入除“12345”以外的任何内容,然后单击下面的链接按钮,您将看到有问题的行为。
  • @MylesFong 我一定会看看的。刚开始工作,所以我想我需要工作 :D 希望你能等一下,稍后我会尽力帮助你:)

标签: angular angular-reactive-forms


【解决方案1】:

请注意the following note placed at the specs for input=number

注意:type=number 状态不适用于碰巧仅包含数字但严格来说不是数字的输入。例如,它不适用于信用卡号或美国邮政编码。确定是否使用 type=number 的一种简单方法是考虑输入控件是否具有旋转框界面(例如,使用“向上”和“向下”箭头)是否有意义。信用卡号的最后一位错了 1 并不是一个小错误,它就像错了每个数字一样。因此,用户使用“向上”和“向下”按钮选择信用卡号是没有意义的。当 spinbox 界面不合适时,type=text 可能是正确的选择(可能带有模式属性)。

我不得不问:为什么不只使用type=text

【讨论】:

  • 谢谢你,这对这个案例很有意义。但是,如果在另一种情况下 type=number 是正确的,例如输入数量,并且需要像我的情况一样的提示值按钮,该怎么办?
猜你喜欢
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 2018-03-13
  • 2020-07-07
  • 2020-09-19
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多