2017-09-25 46 views
1

我得到一個FormBuilder陣列的formControlName得到一個錯誤:無法獲得FormBuilder陣列的formControlName

Error: Cannot find control with path: '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] 
    }); 
} 

這是我的錯誤:

Error: Cannot find control with path: 'elements -> 0 -> name' Trace de la pile : [email protected]http://localhost:4200/vendor.bundle.js:69949:11 [email protected]http://localhost:4200/vendor.bundle.js:69857:9 ../../..

+0

歡迎StackOverflow上。請閱讀[問](https://stackoverflow.com/help/asking)和[我如何問一個好問題](https://stackoverflow.com/help/how-to-ask)。我糾正了你的問題:我簡化了標題(儘可能簡潔!);我使用了所有錯誤消息的blockquotes;我還重寫了句子,刪除了所有無用的部分(例如「請幫助我!」或多個問題/詢問標記)。 –

+0

manu謝謝Massimiliano –

回答

0

我想你打錯因爲忘記打電話給你initAttribut功能:

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

否則FormBuilder將創建一個FormControl陣列,而不是一個FormGroup的陣列。

StackBlitz Example

+0

謝謝uuuu soo much,itis working –