如何使用反应形式来验证禁用的控件(不触发验证)

Fur*_*oud 4 angular angular-reactive-forms

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

      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(...)]);
Run Code Online (Sandbox Code Playgroud)

sum_credit被禁用,因为它的价值时,总是计算。现在,我需要验证sum_credit等于sum_debit,并且我已经在使用validateSomthing函数了。问题是validateSomthing由于控件被禁用,因此未触发。我该如何解决?

谢谢

Fre*_*jck 7

Angular不会触发禁用字段的验证器。解决此问题的一种方法是将验证器应用于组而不是控件(这将触发验证器,以便对对应组中的任何未禁用表单控件的每次更新进行验证:

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(...) });
Run Code Online (Sandbox Code Playgroud)

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

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