I am looking to create a dynamic form using form arrays. When I click on (click)="AddInfoName()"
, it should add a new form.
Here is the HTML code I am using:
<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
<div formArrayName="infoName">
<div class="description" *ngFor="let name of InfoFormGroup.controls; let NameIndex=index" [formGroupName]="NameIndex">
<div [formGroupName]="i" class="row">
<label class="form-line"> Name : </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
<app-filederrors [form]="addinfoForm"
field="getInfoFormGroup(NameIndex)"
nicename="Name">
</app-filederrors>
</div>
</div>
</div>
</form>
And in my TypeScript file, here is the corresponding code:
addinfoForm:FormGroup;
infoNameList:FormArray;
infoModel:Productdetail;
constructor(private fb:FormBuilder,private router:Router,private tokenService:TokenstoreService) { }
ngOnInit() {
this.infoNameList = this.fb.array([]);
this.InfoForm();
}
/**
* AddInfoForm
*/
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
}
get InfoFormGroup(){
return this.addinfoForm.get('infoName') as FormArray;
}
public CreateInfoName():FormGroup{
return this.fb.group({
infoName:['',Validators.compose([Validators.required])]
});
}
public AddInfoName(){
this.infoNameList.push(this.CreateInfoName());
console.log('sdkjfghjkdfgh')
}
public RemoveInfoName(index:number){
this.infoNameList.removeAt(index);
}
getInfoFormGroup(index:number):FormGroup{
const formGroup=this.infoNameList.controls[index] as FormGroup;
return formGroup;
}
AddInfo(){
console.log('in form ==>',this.addinfoForm.value)
}
However, I am encountering two problems with this code:
1 - When creating a new form, I receive the following error:
Error: Cannot find control with path: 'infoName -> 0 -> '
2 - The infoName
array appears to be empty. Even though I create 5 forms, adding data shows an empty array like this:
`infoName: Array(5)
0: {infoName: ""}
1: {infoName: ""}
2: {infoName: ""}
3: {infoName: ""}
4: {infoName: ""}`
What could be causing these issues and how can I resolve them?