【发布时间】:2019-04-07 07:16:04
【问题描述】:
我的 Angular 6 应用程序中有一个反应式表单,在尝试动态创建表单控件时出现错误:
在这种情况下,questionValues 是一个带有多个控件的 FormGroup:
report-create.ts 在 Init 上有以下内容:
this.reportForm = this.fb.group({
// there are other parts to this form which I'm leaving out
questionValues: this.qcs.toFormGroup(this.questions)
});
toFormGroup 与https://angular.io/guide/dynamic-form 中的代码基本相同:
toFormGroup(questions: ReportQuestionBase<any>[]) {
const group: any = {};
questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
: new FormControl(question.value || '');
});
return new FormGroup(group);
}
这是我的html:
<form [formGroup]="reportForm" *ngIf="reportForm">
// once again leaving out the other items
<app-report-questions [questionValues]="reportForm.controls.questionValues"></app-report-questions>
</form>
report-questions.ts 只有一个 Input():
@Input() questionValues: FormGroup;
使用以下html:
<div [formGroup]="questionValues">
<div *ngFor="let question of questionValues.controls" class="form-row">
<mat-form-field>
<input matInput formControlName="question">
</mat-form-field>
</div>
</div>
这会给出错误“找不到类型为 'object' 的不同支持对象 '[object Object]'。NgFor 仅支持绑定到 Iterables,例如数组。”
【问题讨论】:
-
ngfor 遍历数组中的对象,你能检查一下 questionValues.controls 的值是什么
-
这是一个 questionValues 是一个 formGroup 所以 questionValues.controls 是我表单中的所有控件
-
你试过
?
标签: angular