首页 > 解决方案 > 带有父子路由的反应式表单

问题描述

我有一个数据输入表单,我正在使用父/子路由器来定义一个呈现一些选项卡的父组件,每个选项卡加载正在编辑的实体的一部分。

例如:我有一个渲染一些选项卡的组件,每个选项卡路由到一个子路由并渲染模型的一部分(请参见下面的路由)

[
  { 
    path: ':id', 
    component: ParentComponent, 
    resolve: {someModel: SomeModelResolver }, 
    children: [
      { path: '', redirectTo: 'summary', pathMatch: 'full' },
      { path: 'summary', component: SummaryComponent },
      { path: 'other', component: OtherComponent },
      ...
    ]
  }
]

我在所有子组件中使用反应式表单,但遇到了一些麻烦

a)访问所有子路由的数据(我想我可以通过activatedRoute.parent.data来做到这一点),并且;

b)验证所有子路由的数据,因为保存/取消按钮位于父路由组件中

请问有人对我如何实现这一点有任何建议吗?(我更喜欢反应式表单解决方案而不是模板驱动的表单)

标签: angularrouterangular-reactive-forms

解决方案


Another approach which works really well without using router but DI by passing child formGroups via @Input decorators to the child components. Tested this with really huge forms using @angular/material‘s mat-accordion and mat-tab-group. Performance is quite good and the form gets nicely separated into smaller peaces like you want it to.

Create getter functions for these child formGroups

get childform1() {
  return this.form.get(‘childForm1‘) as FormGroup;
}

and then just use

<app-childform [form]=“childform1“&gt;</app-childform>

In your child

 @Input() form: FormGroup;

Then you can save your complete form easily on your parent component and all values will get passed into it nicely.


推荐阅读