如何使用反应式表单验证禁用的控件(不触发验证) [英] How to validate disabled control using reactive forms (validation is not triggered)

查看:27
本文介绍了如何使用反应式表单验证禁用的控件(不触发验证)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的表单结构:

Let's say that I have this form structure:

      this.entryForm = this.formBuilder.group({
            date: [{value:'' , disabled: true}, [Validators.required]],
            notes: [''],
            sum_credit: [{value:'', disabled: true }],   
            sum_debit: [{value:'', disabled: true}],
            items: this.initItems()
          });
// set validation function to sum_credit

   this.entryForm.controls['sum_credit'].setValidators([CommonValidations.validateSomthing(...)]);

sum_credit 被禁用,因为它的值总是被计算.现在我需要验证 sum_credit 是否等于 sum_debit,而且我已经使用 validateSomthing 函数这样做了.问题是 validateSomthing 没有被触发,因为控件被禁用.我该如何解决?

The sum_credit is disabled because it's value is always calculated. Now I need to validate that the sum_credit is equaled to sum_debit, and I'm already doing that using validateSomthing function. The problem is that the validateSomthing is not triggered because the control is disabled. How can I fix that?

谢谢

推荐答案

Angular 不会为禁用的字段触发验证器.解决此问题的一种方法是将验证器应用于组而不是控件(这将在每次更新时触发验证器对相应组内的任何未禁用的表单控件:

Angular doesn't trigger validators for disabled fields. One way to work around this is to apply the validator to the group instead of the control (this will trigger the validator for each update to any, none disabled, form control inside the correspondig group:

this.entryForm = this.formBuilder.group({
    date: [{value:'' , disabled: true}, [Validators.required]],
    notes: [''],
    sum_credit: [{value:'', disabled: true }],   
    sum_debit: [{value:'', disabled: true}],
    items: this.initItems()
  }, { validator: CommonValidations.validateSomthing(...) });

请注意,您需要调整验证器函数以从 sum_debit 控件中读取值:

Note that you need to adapt your validator function to read the value from the sum_debit control:

validateFn(group: AbstractControl) {
  const control = group.get('sum_debit');
  // here you can validate control.value;
}

这篇关于如何使用反应式表单验证禁用的控件(不触发验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆