[英]Angular 4 FormGroup - Pass parent form controls to child component
I am using Angular Reactive Forms FormGroup and FormArray. 我正在使用Angular反应形式FormGroup和FormArray。 I am trying to split out my form fields into child components but am having trouble passing the parent form controls to the child which I feel should simple.
我试图将表单字段拆分为子组件,但是在将父表单控件传递给子组件时遇到了麻烦,我觉得应该很简单。 My parent FormGroup is title 'binsForm' and I am referencing the child component in my template like:
我的父FormGroup的标题为“ binsForm”,我在模板中引用子组件,例如:
<app-child [parent]="binsForm"></app-child>
And then in the child component I have created an @Input property: 然后在子组件中,我创建了一个@Input属性:
@Input() parent: FormGroup;
And then reference that input in the child template: 然后在子模板中引用该输入:
<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>
In the following StackBlitz , you can click on 'edit quality' and you will see in the console the message 'Cannot find control with the name id' 在下面的StackBlitz中 ,您可以单击“编辑质量”,您将在控制台中看到消息“找不到名称为id的控件”
I followed a tutorial for this method but can't figure out why the child component isn't seeing the form group. 我遵循了有关此方法的教程,但无法弄清楚为什么子组件看不到表单组。
I looked at your code and app-child is waiting for its own form and you are trying to inject the parent form which doesn't have the child attributes like id, type, subtype, etc. 我查看了您的代码,app-child正在等待自己的表单,并且您尝试注入不具有id,type,subtype等子属性的父表单。
So instead of inject the parent, just try to inject the child form that comes from your FormArray ( binsFormArray
), like this: 因此,不要注入父对象,而只是尝试注入来自FormArray(
binsFormArray
)的子表单,如下所示:
<app-child [parent]="binsFormArray.at(i)"></app-child>
You need to apply OnChanges on your child component to pickup the new Parent form. 您需要在子组件上应用OnChanges以获取新的Parent表单。
Import OnChanges. 导入OnChanges。
implement it export class ChildComponent implements OnInit, 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.