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

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

问题描述

假设我具有以下表单结构:

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天全站免登陆