Search code examples
angularangular2-formsangular2-formbuilder

Cannot get formControlName of FormBuilder Array


I get an error in getting the formControlName of a FormBuilder Array:

Error: Cannot find control with path: 'elements -> 0 -> name'

<form [formGroup]="targetAttributesForm" (ngSubmit)="save(myForm)">
  <input formControlName="nono" placeholder="First">

  <div formArrayName="elements">
    <div *ngFor="let address of targetAttributesForm.controls.elements.controls; let w=index" class="panel panel-default">
      <div [formGroupName]="w">
        <span>Att {{w + 1}}</span>
        --> {{ address[w] }}
        <label>Attribut name</label><input type="text" formControlName="name">
        <label>Attribut type</label>
      </div>
    </div>
  </div>
</form>

my app.component.ts:

ngOnInit() {
    this.targetAttributesForm = this._fb.group({
       nono : ['a', Validators.required],
       elements : this._fb.array([this.initAttribut]) 
      });
}
initAttribut() {
  return this._fb.group({
        name : ['a', [Validators.required]],
        type : ['b', Validators.required]
    });
}

This is my error:

Error: Cannot find control with path: 'elements -> 0 -> name' Trace de la pile : _throwError@http://localhost:4200/vendor.bundle.js:69949:11 setUpControl@http://localhost:4200/vendor.bundle.js:69857:9 ../../..


Solution

  • I think you have mistyped because forgot to call your initAttribut function:

    this._fb.array([this.initAttribut()])
                                   ^^^^^^
                            you need to call this function
    

    Otherwise FormBuilder will create array of one FormControl instead of array of one FormGroup.

    StackBlitz Example