我想用form array创建一个动态表单。当我单击此COALESCE
时,它会添加表格。
我正在html中使用此代码:
(click)="AddInfoName()"
并在<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"> نام : </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
<app-filederrors [form]="addinfoForm"
field="getInfoFormGroup(NameIndex)"
nicename="نام">
</app-filederrors>
</div>
</div>
</div>
</form>
文件中使用此代码:
ts
此代码有两个问题:
1-创建新表单时,它向我显示此错误:
错误:找不到路径为'infoName-> 0->'
的控件
2-返回 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)
}
。我创建了5个表单,但是当我单击添加数据时,它显示为空
EmptyArray
出什么问题了?我该如何解决问题?
答案 0 :(得分:1)
删除不必要的[formGroupName]
应该是这样
<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 class="row">
<label class="form-line"> نام : </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
<app-filederrors [form]="addinfoForm" field="getInfoFormGroup(NameIndex)" nicename="نام">
</app-filederrors>
</div>
</div>
</div>
</form>