Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了validation – angular2 – 验证父FormGroup的子组件中的FormControlName大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个角度组件对应一个表单/页面生成一个不确定数量的子组件,每个组件代表一个单独的字段,我希望父组件的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

大佬总结

以上是大佬教程为你收集整理的validation – angular2 – 验证父FormGroup的子组件中的FormControlName全部内容,希望文章能够帮你解决validation – angular2 – 验证父FormGroup的子组件中的FormControlName所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。