我在我的角度应用程序中使用了反应形式,其中我使用>>> df1
String_Name START_DATE stop_date
0 Sample String(just a / string) 04/04/2014 ongoing
动态添加了formArray
。但是当我提交表单时,它的值是array的类型数组,但我认为它应该是object的数组。
我的组件代码:
formControl
还有我的html
export class StudentFormComponent {
form;
constructor(private studentService: StudentService,
private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required],
documents: fb.array([])
});
}
get documentCtrl() {
return (this.form.get('documents') as FormArray);
}
addControl() {
this.documentCtrl.push(new FormControl(''));
}
save() {
console.log(this.form);
}
}
答案 0 :(得分:0)
只需将binary
组件中的p-checkbox
属性设置为true
<form [formGroup]="form" (ngSubmit)="save()">
<div class='documents' formArrayName="documents">
<div *ngFor="let control of form.get('documents').controls let i = index">
<p-checkbox
[formControl]="control"
[binary]="true"
>
</p-checkbox>
</div>
</div>
</form>
结果
{ "name": "", "documents": [ true, false, false, true ] }
已更新!♂️
您必须创建一个没有group conformrol的formgroup的formArray,并保存和更改ID或name之类的值作为表单控件
form;
documnets = [ // sample data
{
categoryId: 1,
isSelected: false
},
{
categoryId: 2,
isSelected: false
},
{
categoryId: 3,
isSelected: false
},
]
constructor(
private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required],
documents: fb.array([])
});
}
ngOnInit() {
// add form control base of the data
this.documnets.forEach(doc => this.addControl(doc.categoryId, doc.isSelected));
}
get documentCtrl() {
return (this.form.get('documents') as FormArray);
}
addControl(categoryId: number, isSelected: boolean) {
this.documentCtrl.push(this.fb.group( // create a form group
{
categoryId,
isSelected
}
));
}
save() {
console.log(this.form);
}
tempale
<form [formGroup]="form" (ngSubmit)="save()">
<div class='documents' formArrayName="documents">
<div *ngFor="let doc of form.get('documents').controls" [formGroup]="doc">
<p-checkbox
formControlName="isSelected"
[binary]="true"
[label]="doc.get('categoryId').value"
>
</p-checkbox>
</div>
</div>
</form>
答案 1 :(得分:0)
p-check允许由数组提供。因此,您没有FormArray,只有两个FormControl可以看到stackblitz
this.form = this.fb.group({
name: ['', Validators.required],
documents: [[2,3]] //<--the value of the control will be an array
// but it's not a FormArray
});
还有您的.html
<form [formGroup]="form" (ngSubmit)="save()">
<div class='documents' >
<div *ngFor="let doc of documents; let i = index">
<p-checkbox
<!-- see that, acording the docs, you need use
[formControl]="yourForm.controls['nameOF Control"
-->
[formControl]="form.controls['documents']"
[label]="doc.name"
[value]="doc.value"
>
</p-checkbox>
</div>
</div>
</form>