Before I get into it, I won't be able to share the actual code I'm working on due to confidentiality reasons. However, I can provide a simplified version of the code...
I am working with Angular 7 and Reactive Forms. In my form, I have a radio button that is always visible. When the user selects "yes", another radio button should appear below it. If "no" is selected, the additional radio button should either disappear or be removed from the DOM (using ngIf*).
What I'm aiming to achieve is something like this:
field: ['', { validators: () => { if (this.isElementShown('blah')) { return Validators.required }}}]
Below is the method "isElementShown" that I am using:
isElementShown(id: string) {
var element = document.getElementById(id);
if (document.body.contains(element)) {
return true;
}
return false;
}
Additionally, when the form is submitted, I am checking and logging all invalid fields like this:
const invalid = [];
const controls = this.form.controls;
for (const name in controls) {
if (controls[name].invalid) {
invalid.push(name);
}
}
console.log(invalid);
The issue I am facing is that initially, the field does not show as invalid when the page loads. However, when I select "yes" and the second radio button appears, it is marked as invalid. This is the expected behavior. But when I switch back to "no" for the first radio button, it still appears as "invalid" in the console even though the second radio button is removed from the DOM.
Any suggestions on how to resolve this issue? I feel like I'm close to a solution but I'm stuck at the moment. Thank you for any help!