找不到路径如下的控件:“市场-> 1->市场”

时间:2019-09-13 09:13:17

标签: angular angular6

我在array中有一些市场。我想在文本框中显示该内容,如果要编辑和添加新文本框,则必须这样做。为此,我确实如此

 <div class="field_group" formArrayName="marketplace" >
    <div class="field_group_input last input-icon-plus" *ngFor="let markets of companyDetails.marketplace;let i = index" [formGroupName]="i">                          
  <input type="text" placeholder="Marketplace (eg: Euronext)" formControlName="marketplace" value="{{markets.marketplaceName}}">
   </div>
   </div> 

和Ts

companyDescFormInit() {
    this.companyDescForm = this._fb.group({
      marketplace : this._fb.array( [this.createMrktFields(true)] )
    })
  }
  get formData() { return <FormArray>this.companyDescForm.get('marketplace'); }

  createMrktFields(req:boolean = false): FormGroup {
    return this._fb.group({
      marketplace: ['']
    });
  }

我得到的错误是

 Cannot find control with path: 'marketplace -> 0 -> marketplace'
    at _throwError (forms.js:1775)

Cannot find control with path: 'marketplace -> 1'
    at _throwError (forms.js:1775) 

Cannot find control with path: 'marketplace -> 1 -> marketplace'
    at _throwError (forms.js:1775)

任何人都可以建议我在我的项目中的另一个地方出现相同的错误时犯了什么错误。请帮助我。谢谢

1 个答案:

答案 0 :(得分:1)

您实际上需要将数组中的值放入formarray,然后在模板中对其进行迭代。我也将formData重命名为formArr,因为这样做更有意义。另外,在模板中,如果要为表单控件设置值,请不要使用[value]。 Angular并不关心[value],只关心表单控件中的值。

因此,当您将数据获取到数组(使其异步或同步)时,将对数组进行迭代并创建表单组并推送至表单数组。在这里,我在名称中添加了Validators.required,因为我想您需要它:

this.companyDetails.marketPlace.forEach((x) => {
  this.formArr.push(this._fb.group({
    marketplaceName: [x.marketplaceName, [Validators.required]],
    idMarketplace: [x.idMarketplace]
  }))
})

// ....

get formArr() { return <FormArray>this.companyDescForm.get('marketplace'); }

然后在模板中迭代formarray并通过formControlName="marketplaceName"显示名称:

<div formArrayName="marketplace">
 <div *ngFor="let markets of formArr.controls; let i = index" [formGroupName]="i">
    <input type="text" formControlName="marketplaceName">
 </div>
</div> 

STACKBLITZ