[英]How to get the form from a child component and emit to the parent
I have Parent component with a two childs.我有一个带有两个孩子的父组件。 I want to get the form from the childs and send to the parent everytime that is changed.
我想从孩子那里获取表格并在每次更改时发送给父母。
I have the parent form like this:我有这样的父表单:
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({}),
});
child 1 component:孩子 1 组件:
@Output() onFormEmit = new EventEmitter<any>();
form = new FormGroup({
child1Key1: new FormControl(''),
child1Key2: new FormControl(''),
child1Key3: new FormControl(''),
});
ngOnInit() {
this.onFormEmit.emit(this.form);
}
child 2 component:孩子 2 组件:
@Output() onFormEmit = new EventEmitter<any>();
form = new FormGroup({
child2Key4: new FormControl(''),
child2Key5: new FormControl(''),
});
ngOnInit() {
this.onFormEmit.emit(this.form);
}
After the emit, I want the form to be like this:发出后,我希望表单是这样的:
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
child1Key1: new FormControl(''),
child1Key2: new FormControl(''),
child1Key3: new FormControl(''),
child2Key4: new FormControl(''),
child2Key5: new FormControl(''),
}),
});
And I also want to send the nested form to the child as a Input, so I need to keep the alive conversation between the forms.而且我还想将嵌套表单作为输入发送给孩子,因此我需要保持表单之间的活跃对话。
this is what I have until now: StackBlitz这是我到目前为止所拥有的: StackBlitz
It looks to me like 'nested forms' might be what you're looking for, where the parent formGroup
is passed as an input
to the child component - the controls in the child are added to that在我看来,“嵌套表单”可能就是您正在寻找的,其中父
formGroup
作为input
传递给子组件 - 子组件中的控件被添加到
There's three approaches described in the linked article, the first one is doing the above:链接文章中描述了三种方法,第一种是执行上述操作:
So, why don't you emit child's form.getRawValue()
after each change and when you get this data on the parent's event listener you iterate through object keys and values setting the result form fields?那么,为什么不在每次更改后发出孩子的
form.getRawValue()
并且当您在父母的事件侦听器上获取此数据时迭代对象键和值设置结果表单字段? In the end of the callback just send updated form to children again.在回调结束时,再次将更新后的表单发送给孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.