One of the challenges I am facing is checking the validity of a form located in a child component from a parent component. Ideally, I would like to be able to disable a button on the parent component if the form is invalid, or alternatively, trigger an alert from the parent component when the form is invalid.
To achieve this, I found a solution where I check if the form has the 'ng-invalid' class from the parent component by using a @ViewChild decorator to call a function on the child component. The code looks like this:
Parent Component:
export class CandidateVerificationComponent implements OnChanges, OnInit {
@ViewChild(RightPanelComponent) rightPanelPointer: RightPanelComponent;
saveAndFinish() {
if (this.rightPanelPointer.checkFormValidity())
{
alert('No Valid');
return;
}
this.rightPanelPointer.onSubmit();
}
}
Child Component:
export class RightPanelComponent implements OnChanges , OnInit{
@ViewChild("candiateForm", { read: ElementRef }) tref: ElementRef;
checkFormValidity():boolean {
return (this.tref.nativeElement.className.indexOf('ng-invalid') !== -1);
}
}
While this solution works for now, I am not entirely satisfied as it links the component to the DOM. I believe there must be a smarter approach to handle this.
My idea is to use a template reference variable (#candiateForm), similar to how we can check validity in the submit button below, in the form (child) so that I can verify the validity from the parent component. Is it possible to access that template variable from the parent?
<form (ngSubmit)="onSubmit()" #candiateForm="ngForm" name="candiateForm" (change)="formChanged()">
<div class="form-group">
<label class="control-label" for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" pattern="^[^0-9]+$" required [(ngModel)]='candidate.firstName' name="firstName" #firstName="ngModel">
</div>
<button type="submit" class="btn btn-default" [disabled]="!candiateForm.form.valid">Submit</button>
</form>