我有一個角度組件對應於生成不確定數量的子組件的表單/頁面,每個表示一個單獨的字段,我希望父組件的FormGroup驗證包含在子組件中的字段。只有當我這樣做,我得到一個錯誤:angular2 - 在父FormGroup的子組件中驗證FormControlName
A FormControlName must have a corresponding FormGroup.
這裏是我的父組件的模板代碼:
<div class="form-group" [formGroup]="parentGroup">
<table>
<tbody>
<tr *ngFor="let i of array">
<child [property]="i" [options]="myForm.controls[i.id]"></child>
</tr>
</tbody>
</table>
</div>
的形式在組件文件此處定義。
private formAttrs: FormGroup;
constructor(private _fb: FormBuilder) { }
ngOnInit() {
this.myForm = this._fb.group({});
for (var i = 0; i < this.array.length; i++) {
this.formAttrs.addControl(this.array[i].id, new FormControl(this.array[i].value, Validators.required));
}
}
的子組件的模板代碼是這樣的:
<td class="prompt">
{{i.label}}
</td>
<td class="required" width="1%">
<span *ngIf="property.required">*</span>
</td>
<td>
<input type="text " class="form-control" [ngClass]="{error: !options.valid}" formControlName="property.id">
</td>
<td>
雖然沒有什麼定義,我按了多少孩子的部件我們添加添加FormControls在子組件類(除了「屬性」和傳遞給「選項」的FormControl元素之外),我會認爲父組件中的formGroup將能夠與子組件中的formControlName匹配,但是相反,我得到錯誤:
EXCEPTION: Error in ./ChildComponent class ChildComponent - inline
template:7:109 caused by: formControlName must be used with a parent
formGroup directive. You'll want to add a formGroup directive and pass
it an existing FormGroup instance (you can create one in your class).
有沒有辦法解決這個錯誤?如果沒有,有人可以提出這個問題的另一個解決方案嗎?
在此先感謝。
感謝您的回覆。每一個子組件都有自己的「屬性」成員,它具有唯一的「id」變量,所以formControlNames實際上是不同的。仍然可行? – user2850751