Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormArray. Cannot find control with path

Tags:

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'

like image 839
Aymen Kanzari Avatar asked Oct 25 '18 12:10

Aymen Kanzari


1 Answers

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.
like image 123
EfiBN Avatar answered Nov 15 '22 04:11

EfiBN