So I have a form where a control is required only if another control has a value, for this I created the following structure
profileGroup = this.fb.group({
username: [''],
address: [
'',
[
(control: AbstractControl) => {
if (this.profileGroup?.get('username')?.value) {
return (Validators.required)(control);
}
return (Validators.nullValidator)(control);
},
],
],
});
this function works well, once the username
control gets a value, a Validators.required
is added to the address
control. However, despite the validator being added, the validity of the address
control doesn't update so the control is still marked as valid
.
If possible I would like to avoid using something like
this.profileGroup.get('username')?.valueChanges.subscribe(val=>{
this.profileGroup.get('address')?.updateValueAndValidity()
})
since there may be dynamic controls that I don't know the name of, and don't want to set an observable for each of them.
Here's a stack blitz of a working example https://stackblitz.com/edit/angular-10-formbuilder-example-m8qjq8?file=src/app/app.component.ts