Reputation: 105
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.
Upvotes: 1
Views: 10493
Reputation: 1793
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])
});
}
Upvotes: 0
Reputation: 433
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>
Upvotes: 1