Currently I am working with Angular 4.4.3 reactive forms to create custom validation for a group of controls within a form. As per the documentation on AbstractControl.setErrors, this method updates the errors property of the AbstractControl that it's called upon, and also updates the status of its parent. However, it does not update the parent's errors property. My goal was to set the errors property on a FormGroup instance by using the inherited setErrors method from FormGroup. Surprisingly, it did not update the errors as expected.
Below is a snippet of my code: When trying this approach on FormControl instances, it successfully updates their errors along with their parents' validity status (although the parents' errors remain unaffected):
let myFormGroup
= this._formBuilder
.group({
ctrl1: [null],
ctrl2: [null]
},
{
validator: (fg: FormGroup) => {
let ctrl1 = fg.get('ctrl1'),
ctrl2 = fg.get('ctrl2'),
ctrl1Empty = !ctrl1.value,
ctrl2Empty = !ctrl2.value;
//Successfully sets ctrl1.errors and fg.status, but not fg.errors
if (ctrl1empty)
ctrl1.setErrors({ctrl1required: true});
//Successfully sets ctrl2.errors and fg.status, but not fg.errors
if (ctrl2Empty)
ctrl2.setErrors({ctrl2required: true});
//Doesn't work, doesn't update fg.errors
if (ctrl1Empty && ctrl2Empty)
fg.setErrors({required: true});
}
})
Any insights on why this might be happening?