(Angular 5) Error: Cannot find form control with name:

(Angular 5) Error: Cannot find form control with name:

我正在尝试编辑表单,当我想显示要编辑的值时,使用 setValue 我收到错误消息“错误错误:找不到名称为 purchases 的表单控件。"

component.ts

ngOnInit() {
  this.form = new FormGroup({
      customer: new FormGroup({
        name: new FormControl(),
        lastname: new FormControl(),
        address: new FormControl(),
        phone: new FormControl()
      }),
      createdAt: new FormControl(),
      purchases: new FormArray([])
  });
}

我要编辑的功能

onEdit(invoice) {    
  this.form.setValue(invoice)   
}

component.html

<div class="col-md-8">
    <div formGroupName="customer">
      <h3>Customer</h3>
      <label>Name: <input class="form-control" type="text" formControlName="name"> </label>
      <label>Last Name:<input class="form-control" type="text" formControlName="lastname"></label>
      <label>Phone:<input class="form-control" type="text" formControlName="phone"></label>
      <label>Address:<input class="form-control" type="text" formControlName="address"></label>
   </div>
   <div><li formArrayName="purchases"></li></div>
</div>

View in StackBlitz

控制台中的值

错误是调用setValue()引起的,因为它进行了严格的检查。

您正试图将一个包含多个项目的数组分配给在索引 0 处只有一个初始 FormGroup 的 FormArray。

在索引 1 处分配值失败,因为它不存在。

解决步骤:

  1. 定义表格数组:

    purchases: new FormArray([
        new FormGroup({
            product: new FormGroup({
                categoryS: new FormControl(''),
                location: new FormControl(''),
                name: new FormControl(''),
                price: new FormControl('')
            }),
            quantity: new FormControl('')
        })
    ])
    
  2. 使用patchValue

  3. 清除表格数组:

    while (purchasesFormArray.length) {
       purchasesFormArray.removeAt(0);
    }
    
  4. 循环填充表单数组

    invoice.purchases.forEach(purchase => {
        purchasesFormArray.push(this._fb.group(purchase));
    });  
    

固定代码在这里:View in StackBlitz