0

I am trying to set up a simple FormArray in Angular and am having a hard time getting it to work.

What am I missing?

documentationForm: FormGroup;
documentationArray: FormArray;
defaultDocumentation = 1;

ngOnInit() {
    this.documentationForm = this.formBuilder.group({
       id: this.formBuilder.array([])
    });
}

When a file is added to uploader component, I am calling the following :

fileAddedToQueue(file) {
    this.documentationArray = this.documentationForm.get('id') as FormArray;
    this.documentationArray.push(this.addDocumentType());
}

private addDocumentType(): FormGroup {
    return this.formBuilder.group({ id: this.defaultDocumentation });
}

I put a bunch of console.log and it seems to be working as expected but I cannot get it working with my HTML.

<div formArrayName="id" *ngFor="let file of documentationForm.get('id').controls; let i = index" [formGroupName]="i">
    test
</div>

I get the following :

Unhandled application error. Error: Cannot find control with name: 'id'

What am I doing wrong? Everything seems to be correct from what I can see.

Googlian
  • 6,077
  • 3
  • 38
  • 44
jonpfl
  • 95
  • 2
  • 11

2 Answers2

1

The problem is you are defining the formArray with id: this.formBuilder.array([]), but there should be a control inside formArray.

The correct way is to id: this.formBuilder.array([this.formBuilder.control('')])

Also inside this.formBuilder.array as you directly have this.formBuilder.control, you should not use formGroup in html. Correct way is this:

<div formArrayName="id">
  <div *ngFor="let item of id.controls; let i=index">
      <input type="text" [formControlName]="i">
  </div>
</div>
Sachin Jagtap
  • 423
  • 3
  • 11
  • I need documentationForm to be empty until the user takes an action. The above code adds a formControl upon initialization. – jonpfl Mar 27 '19 at 12:14
  • This answer not correct, because `id.controls` may be return many different types like (FormControl, FormGroup, FormArray), ref: https://stackoverflow.com/a/49395590/2877427 – AnasSafi Jun 22 '22 at 03:50
0

I think that your form initialization is wrong.Please try this:

documentationForm: FormGroup;
documentationArray: FormArray;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {

    this.documentationForm = this.formBuilder.group({
        id: this.formBuilder.array([this.documentationArray])
     });

}
Seba Cherian
  • 1,755
  • 6
  • 18
  • I tried the above but it added a formControl to this.documentationForm upon initialization. I want it to be empty until the user adds a document. – jonpfl Mar 27 '19 at 12:09