Aymen Kanzari
Aymen Kanzari

Reputation: 2013

FormArray. Cannot find control with path

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'

Upvotes: 6

Views: 11356

Answers (2)

EfiBN
EfiBN

Reputation: 408

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.

Upvotes: 4

Eliseo
Eliseo

Reputation: 57909

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">

Upvotes: 2

Related Questions