I have a parent component that includes multiple nested child components. The child components can be conditionally shown or hidden so I need to be able to enable and disable the validators in those child components so that when a child is hidden, its validators don't make the form invalid.
I tried adding public methods on the child components like this:
clearValidators() {
this.formControl.clearValidators();
}
resetValidators() {
this.formControl.setValidators(Validators.compose([
Validators.required,
CustomValidators.existsIn(this.items.map(l => l[this.itemIdField]))
]));
}
And then I call those methods from the parent by getting a reference to the child using @ViewChild(ChildComponent) child: ChildComponent;, but this doesn't work if I use *ngIf to hide the child, because the @ViewChild reference becomes undefined.
I tried changing from *ngIf to [hidden], but that throws the error
Cannot find control with path: 'parent-> child'
I'm not sure why. What is the correct way to handle validators in nested components?
ngIf, could you protect the code for cases wherechildisundefined?childis not defined)?