2

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.
7
  • what are you trying to render? JSON?? Commented Jan 8, 2019 at 9:06
  • 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. Commented Jan 8, 2019 at 9:08
  • can you add the JSON Commented Jan 8, 2019 at 9:10
  • items: Array(3) 0: {image: "1"} 1: {image: "2"} 2: {image: "3"} Commented Jan 8, 2019 at 9:11
  • Can you create stackblitz Commented Jan 8, 2019 at 9:52

1 Answer 1

1

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,
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.