我有两个循环嵌套。第一个循环按预期工作,但是尝试向内部嵌套表单组添加一些字段时,我无法生成这些字段。
我能够按预期生成JSON对象的generate,但无法显示以html模板显示字段:
期望的JSON:
{
content_status: ""
language: ""
post_info: [
{
title: '',
optionType: '',
optionsList: [
{
key: '',
value: '',
}
{
key: '',
value: '',
}
]
}
]
}
<form class="form-horizontal" [formGroup]="pollForm">
<div formArrayName="post_info"
*ngFor="let poll of pollForm.get('post_info').controls; let i = index">
<div [formGroupName] = i>
<div class="row" >
<div class="col-md-12 col-sm-12">
<mat-form-field>
<input type="text" matInput name="title"
placeholder="Poll Question" formControlName="title"/>
<!-- <mat-error *ngIf="!post_info.get('title').valid &&
post_info.get('title').touched">
Enter Poll Question!
</mat-error> -->
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-12">
<mat-form-field>
<mat-select placeholder="Select Options" name="option"
(valueChange)="updateOptions($event, i)">
<mat-option *ngFor="let option of options" [value]="option.value" >
{{ option.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</div>
<div formArrayName="optionsList"
*ngFor="let option of pollForm.get(['post_info', i , 'optionsList']).value; let j = index">
<div [formControlName]=j>
<div class="row">
<div class="col-md-6 col-sm-12" >
<mat-form-field>
<input type="text" matInput placeholder="Add Option Name"
name ="opt_{{i}}" id = "opt_{{i}}" formControlName="answers"/>
</mat-form-field>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
pollForm: FormGroup;
post_info: FormArray;
optionsList: FormArray;
constructor(
private formBuilder: FormBuilder,
) {
this.pollForm = this.formBuilder.group({
post_type: [''],
content_status: [''],
language: [''],
post_info: this.formBuilder.array([this.createPoll()])
});
}
createPoll(): FormGroup {
return this.formBuilder.group({
title: ['', Validators.required],
optionsType: [''],
optionsList: this.formBuilder.array([])
});
}
createOptions(): FormGroup {
return this.formBuilder.group({
value: ['', Validators.required]
});
}
addQuestion(): void {
this.post_info = this.pollForm.get('post_info') as FormArray;
this.post_info.push(this.createPoll());
console.log(this.pollForm);
}
updateOptions(data, i) {
for (let k = 0 ; k < data ; k++) {
this.optionsList = this.pollForm.get(`post_info.${i}.optionsList`) as FormArray;
this.optionsList = new FormArray([]);
this.optionsList.push(this.createOptions());
}