如何在 Angular 中使用多个组件初始化动态表单
我想要一份包含员工轮班的表格。在 UI 中,我有一个表单来指定每天的班次,并且可以动态添加班次。
我希望我的班次组件负责创建单个班次 FormGroup。我正在努力初始化我的父表单,或者我不知道在哪个组件中初始化它。
I want to have a form which contains shift for an employee. In the UI, I have a form to specify a shift for each day and shifts can be dynamically added.
I want my shift component to be responsible for creating a single shift FormGroup. I am struggling to initialise my parent form or I don't know which component to initialise it in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在父组件(即
Working day
)上创建shifts
表单数组,然后将各个数组控件作为FormGroup
传递给子shift
组件。通过将
FormGroup
传递给子组件,您也可以在父组件上访问其值/验证器。注意:正如您所提到的,班次将来自 API,您需要在响应中迭代班次数组并返回结果。使用
startDate
/endDate
属性创建FormGroup
。它的工作原理如下:
Shift component
:将FormGroup
作为输入。在父组件中,创建表单组&迭代
shift
FormArray.controls
。Parent HTML
:TS
:单击按钮/接收 API 响应时,调用addShift()
方法添加新的FormGroup
在shifts
控制中注意: Angular 的最新版本对类型转换非常严格。因此,您可能需要在传递给子级之前将每个
shiftForm
类型转换为父级中的 FormGroup。这是一个有效的 stackblitz演示将
FormGroup
从父级传递给子级。You can create the
shifts
form array on the parent i.e.Working day
component and then pass the individual array controls as aFormGroup
to the childshift
component.By passing
FormGroup
to the child component, you can access its values/validators on the parent also.Note: As you have mentioned, that shifts will be coming from API, you would need to iterate over the shifts array in response & create
FormGroup
withstartDate
/endDate
properties.Here is how it would work:
Shift component
: TakeFormGroup
as an input.In the parent component, create the form group & iterate over the
shift
FormArray.controls
.Parent HTML
:TS
: On button click/ receiving API response, calladdShift()
method to add a newFormGroup
inshifts
controlNote: Recent versions of Angular are strict towards typecasting. Therefore you may need to typecast each
shiftForm
as FormGroup in the parent before passing to the child.Here is a working stackblitz to demonstrate passing
FormGroup
from parent to child.