6

I want to output a form in which one field is an array, and for each element of the array I need to output my inputs.

Component:

ngOnInit() {
  const fb = this.fb;
  this.editForm = this.fb.group({
    country: fb.control(null),
    identifiers: this.fb.array([
       this.fb.group({
         codeIdentifier: fb.control(null),
         numIdentifier: fb.control(null),
       })
    ]),
 });
 this.organizationService.getOneById(this.id).subscribe((organization: Organization) => {
    let ids: any[] = [];
    organization.identifiers.forEach(item => {
       let id: any = { "codeIdentifier": "", "numIdentifier": "" };
       id.codeIdentifier = item.typeIdentifier.code;
       id.numIdentifier = item.numIdentifier;
       ids.push(id);
    });
     this.editForm.setControl('identifiers', this.fb.array(ids || []));
 })
}

HTML:

<div [formGroup]="editForm">
  <ng-container formArrayName="identifiers">
    <ng-container *ngFor="let identifier of identifiers.controls; let i=index" [formGroupName]="i">
      <input type="text" formControlName="codeIdentifier">
      <input type="text" formControlName="numIdentifier">
    </ng-container>
  </ng-container>
</div>

Got error:

Cannot find control with path: 'identifiers -> 0 -> codeIdentifier'

Aymen Kanzari
  • 1,765
  • 7
  • 41
  • 73

2 Answers2

4

Pay attention to set it with the group inside the array as you built it, like that:

this.editForm.setControl('identifiers',
  this.fb.array(ids.map(
      id => this.fb.group({codeIdentifier: id})
    ) || [])
);

this.editForm.setControl('identifiers',
  this.fb.array(ids.map(
      id => this.fb.group({numIdentifier: id})
    ) || [])
);
  • I didn't entirely understood your Objects structure, but this is the way to build the Control Array back to view for Edit/Update purposes.
EfiBN
  • 408
  • 2
  • 11
  • Thank you for the answer :) ... I was passing array of objects ( [{text: 'asfd'}] ) and not array of form groups of such objects - for example like this: arrayOfObjects.map(obj => this.formBuilder.group(obj)) ... :) – pesho hristov Mar 06 '20 at 11:39
  • 1
    Thank you I have been sleepless on wondering what's wrong. This answer solved my problems. I owe you a nice cup of coffee – shifter May 18 '20 at 02:48
2

identifiers is nothing in your code (well the name of a property of a formArray)

You can choose

1.-put a getter in your .ts

get identifiers()
{
    return this.editForm.get('identifiers") as FormArray
}

2.-change your .html

<ng-container *ngFor="let identifier of editForm.get('identifiers").controls;
           let i=index" [formGroupName]="i">
Eliseo
  • 50,109
  • 4
  • 29
  • 67