我正在尝试为每个选定的产品动态提供一组问题。
我已经创建了FormGroup的问题,然后我遍历所选产品并在每个产品下面嵌套问题组。
在某种程度上,这似乎有效。表单已创建,我可以通过JSON管道查看,并可以与它进行交互。
然而,问题是每个产品的所有表单控件都只更新上一个产品的控件(我可以通过{{form.value | JSON}}看到
示例代码:
https://stackblitz.com/edit/angular-py4sam
app.component.ts
import { Component, NgModule, VERSION, OnInit } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormControl, FormGroup, FormArray, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
questionsForm: FormGroup;
qaForm: FormGroup;
questions = [
{
'question': 'like?',
'value': ''
},
{
'question': 'own?',
'value': ''
}
]
products = [
{
'make': 'fender'
},
{
'make': 'gibson'
}
]
createQuestionsForm() {
this.questionsForm = new FormGroup({
questions: new FormArray([])
});
const qArray = <FormArray>this.questionsForm.controls['questions'];
this.questions.forEach((item, index) => {
const aGroup = new FormGroup({
answer: new FormControl(item.question),
value: new FormControl(item.value)
})
qArray.push(aGroup);
})
}
ngOnInit() {
this.createQuestionsForm();
this.qaForm = new FormGroup(
{
qa: new FormArray([])
});
const qaFormArray = <FormArray>this.qaForm.controls['qa'];
this.products.forEach((item, index) => {
const fg = new FormGroup({
make: new FormControl(item.make),
form: this.questionsForm
})
qaFormArray.push(fg);
})
}
}
app.component.html
<h3>FORM</h3>
<form [formGroup]="qaForm">
<div formArrayName='qa'>
<div *ngFor="let prod of products; let productCount = index">
<h3>{{ prod.make }}</h3>
<div [formArrayName]=productCount>
<div formGroupName="form">
<div formArrayName="questions">
<div *ngFor="let q of questions; let qCount = index">
<div [formArrayName]=qCount>
<input type="checkbox" formControlName="value"> {{ q.question }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<p>qaform {{ qaForm.value | json }}</p>
答案 0 :(得分:1)
这里的问题是您对所有产品使用相同的questionsForm
:
const fg = new FormGroup({
make: new FormControl(item.make),
form: this.questionsForm
^^^^^^^^^^^^^^^
})
要修复它,您需要为每个产品创建questionsForm
。
以下是如何实现的目标:
createQuestionsForm() {
const questionsForm = new FormGroup({
questions: new FormArray([])
});
const qArray = <FormArray>questionsForm.controls['questions'];
this.questions.forEach((item, index) => {
const aGroup = new FormGroup({
answer: new FormControl(item.question),
value: new FormControl(item.value)
})
qArray.push(aGroup);
})
return questionsForm;
}
...
this.products.forEach(
...
const fg = new FormGroup({
make: new FormControl(item.make),
form: this.createQuestionsForm()
})
<强> Forked Stackblitz 强>