I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor
.
My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensuring that the parent ngForm
recognizes and applies the validation rules from the child component.
Here's a simplified example illustrating the issue:
Parent Template:
<form #parentForm="ngForm">
<input name="firstName" ngModel required>
<input name="lastName" ngModel required>
<child-component *ngFor="let child of children;"></child-component>
</form>
Child Template:
<div>
<input name="foo" required ngModel>
<input name="bar" required ngModel>
</div>
I've attempted to make the parent form recognize the required
attributes set in the child inputs by placing the child within its own form and passing the instance of #parentForm
to the child, followed by calling:
this.parentForm.addFormGroup(this.childForm.form)
Unfortunately, this approach hasn't yielded the desired results.
Alternatively, I've tried having the parent form fetch the ContentChildren
of the sub forms and integrating each one into the main form. Yet, the validation still doesn't function as expected.
While aware that implementing ControlValueAccessor
in the subcomponent could potentially solve the issue, I prefer not to go down that route as it would entail developing custom validators for existing validations such as required
.
If you have any insights on how I can successfully incorporate a sub-form into the parent while leveraging the child's validation settings, your assistance would be greatly appreciated.