Angular *ngFor over FormGroup in Template - 找不到不同的支持对象错误

Angular *ngFor over FormGroup in Template - Cannot find a differ supporting object error

我正在尝试循环遍历模板中的 FormControl 的 FormGroup。我想为每个显示一个复选框。 这就是我的 component.ts 的样子

tags = ["vegan","vegetarian","meat","fruit","vegetable","seafood","fish","nut"];

get tagsForForm() {
    return this.foodForm.get('tags') as FormGroup;
}

createTagsForForm(): {[key: string]: any} {
    let tagsForForm = {};
    for (let i = 0; i < this.tags.length; i++){
        tagsForForm[this.tags[i]]=false;
    }
    return tagsForForm;
}

ngOnInit(){
    this.foodForm = this.fb.group({
        foodName: [''],
        tags: this.fb.group(this.createTagsForForm())
    });
}

我的 template.html 看起来像这样:

<section formGroupName="tags">
    <h2>Tags</h2>
    <input *ngFor="let tag of tagsForForm" [formControlName]="tag" type="checkbox">
</section>

我在控制台中收到此错误:

"Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

是否无法循环遍历模板中的 FormGroup 或只是缺少某些内容?

您需要使用 keyvalue 管道来遍历对象。尝试以下

<input *ngFor="let tag of tagsForForm | keyvalue" [formControlName]="tag.value" type="checkbox">

属性 的值在 tag.value 中可用,属性 的键在 tag.key 中可用。

更新

看来 this.foodForm.get('tags') as FormGroup 没有 return 要循环的正确对象。您可以尝试将其替换为 this.foodForm.controls['tags']['controls'];。尝试以下

控制器

export class AppComponent  {
  foodForm: FormGroup;
  tags = ["vegan", "vegetarian", "meat", "fruit", "vegetable", "seafood", "fish","nut"];

  get tagsForForm() {
    return this.foodForm.controls['tags']['controls'];
  }

  constructor(private fb: FormBuilder) {}

  createTagsForForm(): {[key: string]: any} {
    let tagsForForm = {};
    for (let i = 0; i < this.tags.length; i++){
      tagsForForm[this.tags[i]] = false;
    }
    return tagsForForm;
  }

  ngOnInit() {
    this.foodForm = this.fb.group({
      foodName: [''],
      tags: this.fb.group(this.createTagsForForm())
    });
  }
}

模板

<form [formGroup]="foodForm">
    <label>Name: </label>
    <input formControlName="foodName" />
    <section [formGroup]="foodForm.controls.tags">
    <ng-container *ngFor="let tag of tagsForForm | keyvalue">
      <label>{{ tag.key | titlecase }}</label>
      <input [formControlName]="tag.key" type="checkbox">
      <br>
    </ng-container>
  </section>
</form>

或者,如果您使用成员变量(此处为 tags)生成嵌套表单组,则可以对其进行循环以避免 getter 和一些额外的开销。以下内容也适用

<form [formGroup]="foodForm">
    <label>Name: </label>
    <input formControlName="foodName" />
    <section [formGroup]="foodForm.controls.tags">
    <ng-container *ngFor="let tag of tags">
      <label>{{ tag | titlecase }}</label>
      <input [formControlName]="tag" type="checkbox">
      <br>
    </ng-container>
  </section>
</form>

工作示例:Stackblitz

使用键值管道,因为您使用的是对象而不是数组

<input *ngFor="let tag of tagsForForm| keyvalue" [formControlName]="tag.value" type="checkbox">

使用此 link 了解更多信息 https://angular.io/api/common/KeyValuePipe