validation – angular2 – 验证父FormGroup的子组件中的FormCon
我有一个角度组件对应一个表单/页面生成一个不确定数量的子组件,每个组件代表一个单独的字段,我希望父组件的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的一部分的执行: 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}}"/> 你的代码使用了不同的变量来绑定formGroup并使用formAttrs,这有点不清楚发生了什么,所以我继续把它们折叠成一个你可以在Plunker中看到它:http://plnkr.co/edit/3MRiO9bGNFAkN2HNN7wg?p=preview (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – Visual Studio 2017 docker错误运行应用程序
- angularjs ui-router路由移除#解决方案
- 解决报错 “build.sh /bin/bash^M: 坏的解释器:没有那个文
- RMI、Hessian、Burlap、Httpinvoker、WebService的比较
- scala – 在Option.isEmpty和Option.get上使用Option.map有
- 【数据结构】第三章 栈与队列
- 公网定制化yum仓库部署
- How to extract a complete list of extension types withi
- Scala:为什么我不能映射一个接受Seq [Char]的函数到一个字
- 关于Bootstrap按钮组件消除黄框的方法