1
votes

I have a main component that contains a child component within it. The main component looks as the following:

<div>
  <h1>Example</h1>
  <app-form-repeater [form]="form" [path]="'items'" [add]="customGroup">
      <ng-template #content>
          <input formControlName="image" placeholder="Item name">
      </ng-template>
  </app-form-repeater>
</div>

Within this component I have a main FormGroup named "form", within here I have a FormArray and within this array I have a FormGroup named "items" within this FormGroup I have a FormControl named "image".

Now I want to loop in my "app-form-repeater" through the FormArray and display the results of my ng-template.

My "app-form-repeater" looks as the following:

<div [formGroup]="form">
  <div formArrayName="items" *ngFor="let item of form.get('items').controls; let i = index;">
    <div [formGroupName]="i">
      <ng-template [ngTemplateOutlet]="content"></ng-template>
    </div>

    <button class="btn btn--red btn--sm btn--round" (click)="removeItem(i)">-</button>
  </div>
</div>

<button class="btn btn--blue" (click)="addItem()">New</button> 

Everything works, I can create new items and it adds the new input. But there is one problem:

ERROR Error: Cannot find control with name: 'image'

This is because it does not use the FormGroup and FormArrayName and FormGroupName from the "app-form-repeater" component.

Is there a way to fix this problem?

Added later:

  1. It looks like ng-template uses parent FormArrayName but not where template is being loaded...
  2. Placing the input directyly in the "app-form-repeater" works but with the ng-template it doesn't.
1
what are you trying to render? JSON??Abhishek Ekaanth
Yeps, I am trying to render FormData. But the problem is that it can't find the FormControlName because the element is within a sub-component.Yanick van Barneveld
can you add the JSONAbhishek Ekaanth
items: Array(3) 0: {image: "1"} 1: {image: "2"} 2: {image: "3"}Yanick van Barneveld
Can you create stackblitzChellappan வ

1 Answers

1
votes

You should define your formArray in the child component something like this:

ngOnInit() {
  this.childForm= this.formBuilder.group({
    items: this.formBuilder.array([ this.addFormItem(item ) ])
  });
}
  createItem(item ): FormGroup {
  return this.formBuilder.group({
    image: item.image,
  });
}