Angular 4 FormGroup - 将 parent 表单控件传递给 child 组件
Angular 4 FormGroup - Pass parent form controls to child component
我正在使用 Angular 响应式表单 FormGroup 和 FormArray。我试图将我的表单字段拆分为 child 组件,但在将 parent 表单控件传递给 child 时遇到了问题,我认为这应该很简单。我的 parent FormGroup 是标题 'binsForm',我在模板中引用 child 组件,例如:
<app-child [parent]="binsForm"></app-child>
然后在 child 组件中我创建了一个 @Input 属性:
@Input() parent: FormGroup;
然后在 child 模板中引用该输入:
<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中,您可以点击'edit quality',您将在控制台中看到消息'Cannot find control with the name id'
我遵循了此方法的教程,但无法弄清楚为什么 child 组件看不到表单组。
您需要在子组件上应用 OnChanges 以获取新的父表单。
导入 OnChanges。
实施它export class ChildComponent implements OnInit, OnChanges {
ngOnChanges(changes) {
console.log('changes', changes);
this.parent = changes.parent;
}
我查看了你的代码,app-child 正在等待它自己的表单,而你正试图注入没有子属性(如 id、类型、子类型等)的父表单
因此,不要注入父级,而是尝试注入来自您的 FormArray (binsFormArray
) 的子窗体,如下所示:
<app-child [parent]="binsFormArray.at(i)"></app-child>
我正在使用 Angular 响应式表单 FormGroup 和 FormArray。我试图将我的表单字段拆分为 child 组件,但在将 parent 表单控件传递给 child 时遇到了问题,我认为这应该很简单。我的 parent FormGroup 是标题 'binsForm',我在模板中引用 child 组件,例如:
<app-child [parent]="binsForm"></app-child>
然后在 child 组件中我创建了一个 @Input 属性:
@Input() parent: FormGroup;
然后在 child 模板中引用该输入:
<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中,您可以点击'edit quality',您将在控制台中看到消息'Cannot find control with the name id'
我遵循了此方法的教程,但无法弄清楚为什么 child 组件看不到表单组。
您需要在子组件上应用 OnChanges 以获取新的父表单。
导入 OnChanges。
实施它export class ChildComponent implements OnInit, OnChanges {
ngOnChanges(changes) {
console.log('changes', changes);
this.parent = changes.parent;
}
我查看了你的代码,app-child 正在等待它自己的表单,而你正试图注入没有子属性(如 id、类型、子类型等)的父表单
因此,不要注入父级,而是尝试注入来自您的 FormArray (binsFormArray
) 的子窗体,如下所示:
<app-child [parent]="binsFormArray.at(i)"></app-child>