[英]How can I pass the FormGroup of a parent component to its child component using the current Form API
[英]Angular 4 FormGroup - Pass parent form controls to child component
我正在使用Angular反应形式FormGroup和FormArray。 我试图将表单字段拆分为子组件,但是在将父表单控件传递给子组件时遇到了麻烦,我觉得应该很简单。 我的父FormGroup的标题为“ binsForm”,我在模板中引用子组件,例如:
<app-child [parent]="binsForm"></app-child>
然后在子组件中,我创建了一个@Input属性:
@Input() parent: FormGroup;
然后在子模板中引用该输入:
<div class="fields-wrap" [formGroup]="parent">
<div class="input-wrap">
<label>Bin ID <span>*</span><input type="text" formControlName="id"></label>
</div>
<div class="clearfix"></div>
</div>
在下面的StackBlitz中 ,您可以单击“编辑质量”,您将在控制台中看到消息“找不到名称为id的控件”
我遵循了有关此方法的教程,但无法弄清楚为什么子组件看不到表单组。
我查看了您的代码,app-child正在等待自己的表单,并且您尝试注入不具有id,type,subtype等子属性的父表单。
因此,不要注入父对象,而只是尝试注入来自FormArray( binsFormArray
)的子表单,如下所示:
<app-child [parent]="binsFormArray.at(i)"></app-child>
您需要在子组件上应用OnChanges以获取新的Parent表单。
导入OnChanges。
实施export class ChildComponent implements OnInit, OnChanges {
ngOnChanges(changes) {
console.log('changes', changes);
this.parent = changes.parent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.