首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角formArray在formArray内

角formArray在formArray内
EN

Stack Overflow用户
提问于 2022-02-19 18:02:55
回答 1查看 462关注 0票数 0

我在我的项目中进行内联编辑,我试图对来自服务器的数据进行修补,我在accountNumbers数组的formarray中设置了格式数组,但是当我试图更改输入值时,它会产生错误: Error:无法找到路径控制:‘键入-> options -> 0 -> accountNumbers -> accountNumber’--我做错了什么?这是我的stackblitz

.ts

代码语言:javascript
复制
    this.editCompanies = this._formBuilder.group({
      type: this._formBuilder.group({
        options: this._formBuilder.array([]),
      }),
    });

    const control = <FormArray>this.editCompanies.get('type.options');
    this.items.forEach((x) => {
      control.push(
        this.patchValues(x.name, x.identificationCode, x.accountNumbers)
      );
      console.log(control);
    });
  }

  patchValues(name, identificationCode, accountNumbers) {
    return this._formBuilder.group({
      name: [name],
      identificationCode: [identificationCode],
      accountNumbers: new FormArray([this.initOptions()]),
    });
  }

  initOptions() {
    return new FormGroup({
      accountNumber: new FormControl(''),
    });
  }

.html

代码语言:javascript
复制
  <div class="col-lg-5 accountNumbers">
    <span formArrayName="accountNumbers">
        <span class="value" [ngClass]="{'my_class': hidemeSub[index] === true}"
        [hidden]="hidemeSub[index]"> {{item.accountNumbers}}</span>
        <input type="text" class="form-control" formControlName="accountNumber" [hidden]="!hidemeSub[index]">
    </span>
  </div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-19 18:34:30

如果查看路径,就会发现缺少了第二个FormArray的elemento索引。

键入-> options -> 0 -> accountNumbers -> missing_index -> accountNumber

类似于使用以下方法分配第一个FormArray索引:

代码语言:javascript
复制
<div class="example-accordion-item-header nusx row" formArrayName="options"
    *ngFor="let item of items; let index = index;">
    <ng-container [formGroupName]="index">

您还需要循环遍历第二个数组项,并使用正确的_Control_Name指令分配第二个索引。由于它也是一个FormGroup数组,所以可以这样做:

代码语言:javascript
复制
<ng-container 
  *ngFor="let accountNumber of item.accountNumbers; let accIndex = index" 
  [formGroupName]="accIndex"
>
  <input type="text" class="form-control" formControlName="accountNumber" [hidden]="!hidemeSub[index]">
</ng-container>

编辑

您还需要正确初始化帐号的FormGroup,为每个帐户创建一个组:

代码语言:javascript
复制
patchValues(name, identificationCode, accountNumbers) {
  return this._formBuilder.group({
    ...
    accountNumbers: new FormArray(
      accountNumbers.map((account) => this.createAccountControl(account))
    ),
  });
}


//I renamed the method initOptions to better reflect the purpose
createAccountControl(initialValue: string = '') {
  return new FormGroup({
    accountNumber: new FormControl(initialValue),
  });
}

干杯

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71187708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档