What is the reason for the following error: Error: Cannot find control with path: 'resources -> 0 -> name'
I try to implement form array in a form, this array contains a collection of form groups, here is the implementation
component
form: FormGroup = this.formBuilder.group({
name: ['', Validators.required],
description: ['', [Validators.required, Validators.maxLength(255)]],
resources: this.formBuilder.array([]),
});
a getter for resources
get resources(): FormArray {
return this.form.get('resources') as FormArray;
}
add resource method
private newResource(): FormGroup {
return this.formBuilder.group({
title: ['', Validators.required],
description: ['', [Validators.required, Validators.maxLength(255)]],
contentTypeId: ['', Validators.required],
url: ['', Validators.required],
});
}
addResource(): void {
this.resources.push(this.newResource());
}
template
<ng-container formArrayName="resources">
<div *ngFor="let resource of resources.controls; let i = index">
<ng-container [formGroupName]="i">
<div class="field">
<input
pInputText
formControlName="name"
class="p-inputtext w-full"
/>
</div>
<div class="field">
<textarea
pInputTextarea
formControlName="description"
class="p-inputtext w-full"
></textarea>
</div>
</ng-container>
</div>
</ng-container>
Adding a resource expects the form element to be drawn and the model to be updated. The latter happens but because of adding the form group the following error occurs, the layout breaks:
ERROR Error: Cannot find control with path: 'resources -> 0 -> name'
I have tried variations of this answer but the error persists.
update 0
This answer suggests adding [formGroup]
but when I try I get this error:
error TS2740: Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.
Solution 1:
As requested by Post Owner,
Issue
The name
control doesn't exist in the FormGroup
of newResource()
.
<input
pInputText
formControlName="name"
class="p-inputtext w-full"
/>
FormGroup
private newResource(): FormGroup {
return this.formBuilder.group({
title: ['', Validators.required],
description: ['', [Validators.required, Validators.maxLength(255)]],
contentTypeId: ['', Validators.required],
url: ['', Validators.required],
});
}
Solution
Hence, replace it with formControlName="title"
in the HTML.
Make sure that all the formControlName
in the HTML exist in the FormGroup
.
Sample Demo