我有一个 Angular 组件对应于生成不确定数量的子组件的表单/页面,每个子组件代表一个单独的字段,我希望父组件的 FormGroup 验证子组件中包含的字段。只有当我这样做时,我才会收到错误消息:
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>
表单在这里的组件文件中定义。我根据要添加的子组件数量添加 FormControls:
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>
虽然子组件类中没有定义任何内容(除了“属性”和为“选项”传递的 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).
有什么办法可以解决这个错误吗?如果没有,有人可以建议这个问题的另一种解决方案吗?
提前致谢。
最佳答案
我在 Plunker 中遇到了一些实现这个的事情。
首先,我们需要将我们的 formGroup 从父级传递给子级,这样我们就有了一个 FormGroup 来满足模板引擎强制执行 FormControls 作为 FormGroup 的一部分:
child.component.ts
@Input() parentGroup: FormGroup;
child.component.html
<td [formGroup]="parentGroup">
<...>
</td>
然后我们还需要设置[formControl]
或评估property.id
,否则它会查找名称“property .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}}"/>
您的代码使用不同的变量绑定(bind) formGroup
并使用 formAttrs
这有点不清楚发生了什么所以我继续将它们折叠成一个和你可以在 Plunker 中看到:http://plnkr.co/edit/3MRiO9bGNFAkN2HNN7wg?p=preview
关于validation - angular2 - 在父 FormGroup 的子组件中验证 FormControlName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40671737/