如果你使用 ReactiveForm,你需要使用 FormArray
FormArray 可以是 FormControl 或 FormGroup
FormControls 的 FormArray
constructor(private fb:FormBuilder) {}
ngOnInit() {
//We create an array of FormControl, each question a FormControl
let data:FormControl[]=this.questions.map(q=>new FormControl());
this.myform=this.fb.group({
questions:new FormArray(data)
})
}
//the .html
<!--we use *ngIf to show the form only when we create the form-->
<div *ngIf="myform" [formGroup]="myform">
<!--we iterate to myForm.get('questions').controls -->
<!--we use our variable "questions" to show the label and options-->
<div *ngFor="let question of myform.get('questions').controls;let i=index">
<label>{{questions[i].question}}</label>
<select required [formControl]="question" >
<option value="null" disabled="disabled">Option</option>
<option *ngFor="let option of questions[i].options">{{option}}</option>
</select>
</div>
</div>
<!--just for check-->
{{myform?.value |json}}
如果我们使用 formGroup 数组,我们会改变一些东西
constructor(private fb:FormBuilder) {}
ngOnInit() {
//we create and array of FormGroup
let data2:FormGroup[]=this.questions.map(q=>this.fb.group({
option:null
}));
this.myform2=this.fb.group({
questions:new FormArray(data2)
})
}
<div *ngIf="myform2" [formGroup]="myform2">
<!--see that we say to Angular the "formArrayName" -->
<div formArrayName="questions">
<div *ngFor="let question of myform2.get('questions').controls;
let i=index" [formGroupName]="i"> <!--don't forget formGroupName-->
<label>{{questions[i].question}}</label>
<!--the select use formControlName, our array is an array of FormGroup-->
<select required formControlName="option" >
<option value="null" disabled="disabled">Option</option>
<option *ngFor="let option of questions[i].options">{{option}}</option>
</select>
</div>
</div>
</div>
{{myform2?.value |json}}
声明:@FrontEndDeveloper。一件事是我们用来制作问题的数组问题。(也许我必须为变量选择其他名称),另一件事是表单的值。 myform1 的值={questions:["20","1"]},myform2 的值={questions:[{option:"20"},{option:"2"}]}。
当我们创建一个 FormControl 数组(或一个 FbGroup 数组)时,我使用了 map,同样我可以做一些类似的操作
let data:FormControl[]=[];
data.push(new FormControl());
data.push(new FormControl());
或
let data2:FormGroup[]=[];
data2.push(this.fb.group({
option:null
}));
data2.push(this.fb.group({
option:null
}));
通常我们有一些数据来初始化表单。 (带有一些数据的对象)我们从 dbs 获得的
//Imagine we have mydata{name:"A",options=["20","1"]}
//we can map this data to create the form
let data:FormControl[]=this.mydata.options.map(q=>new FormControl(q));
//or
let data2:FormGroup[]=this.mydata.options.map(q=>this.fb.group({
option:q
}));
//Imagine we have mydata{name:"A",options=[{option:"20"},{option:"1"}]}
//we can map this data to create the form
let data:FormControl[]=this.mydata.options.map(q=>new FormControl(q.option));
//or
let data2:FormGroup[]=this.mydata.options.map(q=>this.fb.group({
option:q.option
}));