Search code examples
javascriptangularangular-reactive-formsangular-forms

Cannot find control with path when displaying dynamic FormControlNames - Angular Reactive Forms


I have built a reactive form where the form gets built dependant of the data.

stackBlitz demo

In my example a user selects an option from a <select> this triggers a (change) method that gets more data which may add more fields to the form via addControl.

<div formArrayName="fields">
  <ng-container
    *ngFor="let item of fields; let i = index"
    formGroupName="linkTypeAttributeForm"
  >
    <!-- this could be anything -->
    <input [type]="item.dataType" [formControlName]="item.displayName" />
  </ng-container>
</div>

Are there any better ways to have built this implementation to allow me to specify the type and add an unknown formControlName? Any help appreciated!

I'm getting an Error Cannot find control with path: 'fields -> linkTypeAttributeForm -> issue.

Anybody know how to solve this?

stackBlitz demo


Solution

  • You will want to change:

    formGroupName="linkTypeAttributeForm"
    

    to

    [formGroup]="linkTypeAttributeForm"
    

    formGroupName would be used for a nested FormGroup that always has a fixed name, e.g.

    const someForm = new FormGroup({
      someControl: new FormControl(),
      someNestedFormGroup: new FormGroup({
        someNestedControl: new FormControl()
      })
    })
    
    <form [formGroup]="someForm">
      <ng-container formGroupName="someNestedFormGroup">
        ...
      </ng-container>
    </form>
    

    Because your linkTypeAttributeForm isn't actually nested inside linkTypeForm, it's effectively it's own top-level form, so it needs to be bound to the template as with other top-level forms, e.g. via [formGroup]