I am using angular 7 appplication and i am writing a generic dynamic form creator. I am using reactive forms and ng-template and <ng-container *ngTemplateOutlet>
for recursively displaying the form element.The code of the project could be seen Here.
But i am facing the following error
ERROR Error: Cannot find control with name: 'data'
at _throwError (forms.js:1775)
at setUpControl (forms.js:1683)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4532)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5030)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4980)
at checkAndUpdateDirectiveInline (core.js:9239)
at checkAndUpdateNodeInline (core.js:10507)
at checkAndUpdateNode (core.js:10469)
at debugCheckAndUpdateNode (core.js:11102)
at debugCheckDirectivesFn (core.js:11062)
But if i see my formGroup object i can see a control with data as the name of the control as shown below.
What is the mistake i am doing ? Please help.
Reproduction of the problem is Here stackblitz
You're right there is a problem with ng-template here.
FormControlName
directive heavily relies on hierarhy of elements above current element to determineFormControl
. Since you're usingngTemplateOutlet
this hierarhy mixed up and Angular can't find parentFormGroup
orFormArray
controls.You can refactor your example to use nested components and it should work if you will keep hierarhy of child
AbstractControls
.On the other hand, you can make it work with
ngTemplateOutlet
if you will use FormControl directive. You need to only make sure you provided correct control to yourinput
element.Here's how it could be done:
The key point here is to get correct
path
to destination control which I'm passing as part of context to next child level.Also if you want to generate infinity structure nested elements you should refactor your code for building FormGroup:
Ng-run Example