无法获取FormBuilder数组的formControlName

时间:2017-09-25 18:03:37

标签: angular angular2-forms angular2-formbuilder

我在获取formControlName数组的FormBuilder时遇到错误:

  

错误:找不到路径控制:'元素 - > 0 - >名称'

<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]
    });
}

这是我的错误:

  

错误:找不到路径控制:&#39;元素 - &gt; 0 - &gt;命名&#39;   Trace de la pile:   _throwError @ http://localhost:4200/vendor.bundle.js:69949:11   setUpControl @ http://localhost:4200/vendor.bundle.js:69857:9   ../../..

1 个答案:

答案 0 :(得分:1)

我认为您输入错误是因为忘记拨打initAttribut功能:

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

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

<强> StackBlitz Example