【问题标题】:Cannot get formControlName of FormBuilder Array无法获取 FormBuilder 数组的 formControlName
【发布时间】:2018-03-06 19:02:05
【问题描述】:

我在获取 formControlNameFormBuilder 数组时出错:

错误:找不到带有路径的控件:'elements -> 0 -> name'

<form [formGroup]="targetAttributesForm" (ngSubmit)="save(myForm)">
  <input formControlName="nono" placeholder="First">

  <div formArrayName="elements">
    <div *ngFor="let address of targetAttributesForm.controls.elements.controls; let w=index" class="panel panel-default">
      <div [formGroupName]="w">
        <span>Att {{w + 1}}</span>
        --> {{ address[w] }}
        <label>Attribut name</label><input type="text" formControlName="name">
        <label>Attribut type</label>
      </div>
    </div>
  </div>
</form>

我的 app.component.ts:

ngOnInit() {
    this.targetAttributesForm = this._fb.group({
       nono : ['a', Validators.required],
       elements : this._fb.array([this.initAttribut]) 
      });
}
initAttribut() {
  return this._fb.group({
        name : ['a', [Validators.required]],
        type : ['b', Validators.required]
    });
}

这是我的错误:

错误:找不到带有路径的控件:'元素 -> 0 -> 名称' 追踪 de la pile : _throwError@http://localhost:4200/vendor.bundle.js:69949:11 设置控制@http://localhost:4200/vendor.bundle.js:69857:9 ../../..

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读AskingHow do I ask a good question。我更正了您的问题:我简化了标题(尽可能简洁!);我对所有错误消息都使用了块引号;我还重写了你的句子,删除了所有无用的部分(例如“请帮助我!”,或多个问号/问号)。
  • manu 感谢马西米利亚诺

标签: angular angular2-forms angular2-formbuilder


【解决方案1】:

我认为您输入错误是因为忘记调用您的 initAttribut 函数:

this._fb.array([this.initAttribut()])
                               ^^^^^^
                        you need to call this function

否则FormBuilder 将创建一个包含一个FormControl 的数组,而不是一个包含一个FormGroup 的数组。

StackBlitz Example

【讨论】:

  • 我们可以在元素内部使用 FormControl 数组而不是 FormGroup 吗?
  • @Nitul 这取决于你。如果你愿意,你可以
  • 我试过但没有工作,可能是我身边缺少的东西。我尝试定义 formControlName="w" 并删除了 formGroupName。
  • @Nitul 你能用 stackblitz 准备一个小演示吗?
猜你喜欢
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2021-10-10
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多