My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" to set up a listener on the fields and implementing the logic inside the listener. After applying the logic within the listener, the method "updateValueAndValidity()" should be called.
However, an issue arises when I include "updateValueAndValidity()"; it triggers a Recursion Error in the browser. I'm puzzled as to why this error occurs since I don't see any recursion in my code. It seems like "updateValueAndValidity()" might be causing the listener to trigger again.
If I exclude "updateValueAndValidity()", the recursion error disappears but the desired logic doesn't function properly. I'm stuck on how to resolve this problem, so I'm seeking some guidance. Can anyone assist me?
isFormEmpty: boolean = true;
addressForm: FormGroup;
onChanges() {
let street = this.addressForm.get('street');
let streetNumber = this.addressForm.get('streetNumber');
let zipCode = this.addressForm.get('zipCode');
this.addressForm.valueChanges.subscribe(val => {
console.log(val);
this.isFormEmpty = true;
if (val.street !== '') {
this.isFormEmpty = false;
} else if (val.streetNumber !== '') {
this.isFormEmpty = false;
} else if (val.zipCode !== '') {
this.isFormEmpty = false;
}
if (!this.isFormEmpty) {
street.setValidators([Validators.required, Validators.maxLength(36)]);
streetNumber.setValidators([Validators.required, Validators.maxLength(10)]);
zipCode.setValidators([Validators.required, Validators.maxLength(10)]);
} else {
street.setValidators([Validators.maxLength(36)]);
streetNumber.setValidators([Validators.maxLength(10)]);
zipCode.setValidators([Validators.maxLength(10)]);
}
street.updateValueAndValidity();
streetNumber.updateValueAndValidity();
zipCode .updateValueAndValidity();
});
}
ngOnInit() {
this.addressForm = this.formBuilder.group({
street: ['', Validators.maxLength(36)],
streetNumber: ['', Validators.maxLength(10)],
zipCode: ['', Validators.maxLength(10)]
});
this.onChanges();
}