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(...)]);
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?
Thanks
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(...) });
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With