2016-11-18 184 views
3

我有一個角度組件對應於生成不確定數量的子組件的表單/頁面,每個表示一個單獨的字段,我希望父組件的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). 

有沒有辦法解決這個錯誤?如果沒有,有人可以提出這個問題的另一個解決方案嗎?

在此先感謝。

回答

1

這裏的問題是,在一個表單組中不可能有多次具有相同的表單控件名稱。

您需要爲每個子組件聲明一個自己的表單組,然後可以根據您的引用屬性在父組件中迭代它。您可以使用指令組件方法FormGroupDirective.getControl(controlName)獲得每個子窗體控件,如您在文檔中所見:https://angular.io/docs/ts/latest/api/forms/index/FormGroupDirective-directive.html

+0

感謝您的回覆。每一個子組件都有自己的「屬性」成員,它具有唯一的「id」變量,所以formControlNames實際上是不同的。仍然可行? – user2850751

6

我遇到了一些在Plunker中實現此功能的事情。

首先,我們需要從父在我們formGroup傳遞給孩子,所以我們有一個FormGroup滿足FormControls是一個FormGroup的一部分的模板引擎的執法:

child.component。 TS

@Input() parentGroup: FormGroup; 

child.component.html

<td [formGroup]="parentGroup"> 
<...> 
</td> 

然後我們還需要設置[formControl]評估property.id,否則它會查找名稱「屬性」。ID「:

<input type="text " class="form-control" [ngClass]="{error: !options.valid}" [formControl]="options"/> 

<input type="text " class="form-control" [ngClass]="{error: !options.valid}" formControlName="{{property.id}}"/> 

你的代碼是用不同的變量綁定formGroup和使用formAttrs這是爲了什麼事情,所以我徑自有點不清楚,他們昏倒一個你可以在Plunker中看到:http://plnkr.co/edit/3MRiO9bGNFAkN2HNN7wg?p=preview

+0

由於某種原因,與formControlName的數據綁定在我的情況下不起作用,但您的formControl示例完美地工作 – Anonymous

相關問題