1
votes

I am using a meta-data object to dynamically create a very large form (~400 inputs, though a small sample is shown in stackblitz example). I need to use the meta-data structure to carry input-specific information to the inputs (i.e. type of input, select options, step size, etc). When my html ng-template gets called recursively inside of a and subsequently , the parent form is not recognized. When I get past the initial recursion level, the ReactiveForm cannot trace to the desired formGroup.

Essentially, the formGroupName appears to be unable to traverse through levels of the recursive template.

I have been spinning my wheel for a while trying to get this functional, but to no avail.

I have a stackblitz example of what I am trying to do.

https://stackblitz.com/edit/angular-jndvkb

Any help figuring out why the path down through the FormGroup does not work inside of the templates would be greatly appreciated.

1
Looks pretty complicated. I would avoid this setup at all. Have you looked into FormArray or this for dynamic form fields?robert
@robert I was trying to use just FormArrays, but my inputs will vary between type=text, type=number, select, and checkbox. I don't believe there is anywhere in the formControl that I can store meta-data needed to distinguish between them. My primary question is in the html, with calling a template inside of the div with formGroupName, and then having the controls of that formGroup available to be called inside of that template (ie, the recursiveness that I need)Chris Reed
also noting that my end result will have inputs at different nesting levels, and formGroups and formControls at the same nesting level as each other.Chris Reed

1 Answers

0
votes

For whatever reason, the formGroupName could not reach into the ng-container. To remedy this, I moved the formGroupName to the top of the ng-template, and changed it to [formGroup]. The formGroup instance is passed into the ng-template and the nested/recursive forms are created there.

Solution stackblitz: https://stackblitz.com/edit/angular-k9saz2

I still do not know the root-cause of the issue, but now I have a form that generates recursively from an initial formGroup, and has all the validators tied to each input. I also have access to the meta-data structure to render my inputs as I need to.

I can also easily add/remove/edit inputs by only changing the initial formGroup declaration in my constructor. This makes maintenance very easy down the road.

The next step for me would be to move all the formGroup and meta-data generation to a service, and have them passed into this component as Inputs, so I can re-use this template for different groups of forms.