Angular 9中复选框的反应形式数组

问题描述 投票:0回答:1

我有一系列返回给对象的产品,它们看起来像:

{"opportunityId":2, "customer":"Graham's Motors",..."products":[{"id":1,"name":"Optoin 1","selected":false},{"id":2,"name":"Option 2","selected":false},{"id":3,"name":"Option 3","selected":true},...

我有一个导入的打字稿文件:

import { FormControl, FormGroup, FormArray } from '@angular/forms';

并且我创建一个这样的FormGroup:

opportunityForm = new FormGroup({
    partner: new FormControl(''),
    customer: new FormControl(''),
    ...
    products: new FormArray([])

我正在使用API​​调用来填充以这种方式获取的数据:

this.dataService.getOpportunity(this.id)
  .subscribe(data => {
    this.opportunityForm.setValue({
      partner: data.partner ?? '',
      customer: data.customer ?? '',
      ...
      });
    data.products.forEach(product => {
      (<FormArray>this.opportunityForm.get('products')).push(new FormControl(product));
    });

我认为可以正确地将产品作为表单数组放置。我的问题似乎是如何构造html。当前它看起来像:

<div class="col" formArrayName="products">
  <div *ngFor="let option of products; index as i" >
    <label>
      <input type="checkbox"
        name="option.name"
        value="{{option.value}}" 
        [formControlName]="i"                                       
        [checked]="option.selected"
        (change)="option.selected = !option.selected"/>
      {{option.name}}
    </label>
  </div>   
</div>

我收到一个错误:

错误错误:必须为名称为'products'的表单控件提供一个值。

但是我看不到我在做什么错。谢谢你的帮助。我只想显示一个复选框列表,其中包含是否已选中它们(有一个编辑表单),然后允许用户在将其发回表单之前对其进行更新。

angular angular-forms reactive-forms
1个回答
0
投票

您需要将表单声明为组件的类成员:

export class HelloComponent implements OnInit {
  opportunityForm;

      ngOnInit() {
        this.opportunityForm = new FormGroup({
          partner: new FormControl(''),
          customer: new FormControl(''),
          products: new FormArray([])
        });
      }
}

然后您通过模板访问它:

  <div class="col" formArrayName="opportunityForm.products">
  <div *ngFor="let option of opportunityForm.products; index as i" >
  ....
© www.soinside.com 2019 - 2024. All rights reserved.