【问题标题】:Error when iterating through FormGroup in Angular Reactive Form在 Angular Reactive Form 中迭代 FormGroup 时出错
【发布时间】: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


【解决方案1】:

questionValues.controls 是一个 formGroup 对象,它不是一个 formArray。您不能使用 *ngFor。您可以尝试 keyValue 管道或 Object.keys() 方法。

<div [formGroup]="questionValues">
  <div *ngFor="let questionkey of Object.keys(questionValues.controls)" class="form-row">
    <mat-form-field>
      <input matInput formControlName="questionValues.controls[questionkey]">
    </mat-form-field>
  </div>
</div>

【讨论】:

  • 好的,谢谢,这很有帮助 - 我应该自己迭代 wuestionValues.controls 还是 questionValues?
猜你喜欢
  • 2021-04-19
  • 1970-01-01
  • 2020-04-07
  • 2022-12-27
  • 2019-12-26
  • 2018-10-12
  • 1970-01-01
  • 2018-07-01
  • 2018-04-27
相关资源
最近更新 更多