ERROR Error: Cannot find control with path: Angular FormArray

ERROR Error: Cannot find control with path: Angular FormArray

我正在创建匿名 formArray 输入(自动完成)以使用 autocomplete 查找项目。

添加自动完成后,自动完成输入不起作用,尽管它可以独立工作。

错误信息是 ERROR Error: Cannot find control with path: 'orderItems -> 0 -> search'

你能帮我改进代码吗?

谢谢。

 <form [formGroup]="orderForm">
    <div formArrayName="orderItems">
      <div *ngFor="let orderItem of getControls(); let i = index" [formGroupName]='i'>
        <p-autoComplete
        formControlName="search"
        (onSelect)="onSelect($event)"
        [suggestions]="list">
        </p-autoComplete>
      </div>
    </div>
    <p-button (click)="onAdd()"> add </p-button>
</form>
public orderItems = new FormArray([])
public orderForm: FormGroup;

ngOnInit(): void {
    this.orderForm = new FormGroup({
      'orderItems': this.orderItems,
      search: this.fb.array([
        this.fb.control('')
      ])
    });

    this.orderForm
    .get('search')
    .valueChanges.pipe(debounceTime(1000))
    .subscribe((value) => {
      if(value === '') {return null};
      this.getList(value)
    })
}

  getControls() {
    return (<FormArray>this.orderForm.get('orderItems'))
    .controls;
  }

  get search() {
    return this.orderForm.get('search') as FormArray;
  }

最初使用空数组设置表单

buildForm() {
    this.orderForm = this.fb.group({
      orderItems: this.fb.array([]),
    });
  }

然后获取数组的数据并填充数组

setOrderItemArray() {
    const orderItemsArray = this.orderForm.get('orderItems') as FormArray;
    this.orderItemsList.forEach(item => {
      orderItemsArray.push(this.buildOrderItemsForm(item))
    });
  }

  buildOrderItemsForm(item): FormGroup {
    return this.fb.group({
      id: item.id,
      search: item.search,
      name: item.name
    })
  }

现在您在数组的每个对象中都有一个 'search' 的实例,并且可以为每个单独使用搜索自动完成。