javascript - 嵌套的 ReactiveForms 控件没有获得 ngSubmit 事件

标签 javascript angular dependency-injection angular-reactive-forms

在构建更复杂的响应式表单时,我在多次嵌套 reactiveFormGroups 时偶然发现了一个问题。

所以我有两种情况:

  1. 表单组件 -> 表单局部组件 -> 自定义输入组件

  2. 表单组件 -> 自定义输入组件

目标是监听自定义输入组件中的 ngSubmit 事件以显示其错误状态。

在我的自定义输入组件中,我通过 @Host() 装饰器注入(inject) ReactiveFormsDirective。但是,如果组件像场景 1 中那样嵌套,则它永远不会收到任何事件。

我的猜测是,这种情况下的问题与它试图获取的“错误”ControlContainer 有关。 @Host() 只是查找注入(inject)器链,直到它到达主机,而不是进一步。然而,这个 FormControlDirective 对表单提交一无所知。

如果这是真的,我会尝试将 ControlContainer 传递给分部组件以使其可用于输入组件。 viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective } ]

不幸的是,这没有按预期工作。

为了使这更具体,我在这里创建了一个基本示例:https://stackblitz.com/edit/angular-7rmpvt

如果能在这里得到一些帮助,了解为什么会这样,以及如何创建一个好的解决方案,那就太好了。

最佳答案

正如 Kara 所说,处理复杂的响应式表单时的主要思想是我们应该在顶层只定义一个 [formGroup] 指令

For nested FormGroups, you'd want to use formGroupName instead to ensure that the nested group value and validation status are properly synced to the parent group's value and validation status, among other things.

So if you do have a nested [formGroup], it typically indicates that you have a nested form that is not related to the parent form. It's another top-level form that will not be connected to its parent's model. This is a relatively common pattern because, for CSS / positioning reasons, you might have a sub-form that happens to be within the form tags of another form, but is unrelated (e.g. a shopping checkout form with a "newsletter sign-up" sub form).

https://github.com/angular/angular/issues/21263#issuecomment-357074997

还有 Unresolved 问题 https://github.com/angular/angular/issues/21823

考虑到这一点,我们可以通过提供 ControlContainer

解决您提到的问题
AppComponent [formGroup]
   ||
   \/
FormPartialComponent
  1) add viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective } ]
  2) remove [formGroup]
   ||
   \/
FormInputComponent
 remove @Host

这样我们就可以轻松地在 FormPartialComponent 中使用 formControlName,而 FormInputComponent 将获得顶级 FormGroupDirective

为了让这更具体,我更新了您的 Stackblitz Example

另见:

关于javascript - 嵌套的 ReactiveForms 控件没有获得 ngSubmit 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53322974/

相关文章:

javascript - VueJS 中的 AJAX 数据更新后 DOM 不更新

javascript - angularjs 在请求前检查数据

javascript - 使用 jquery 和 javascript 创建一个 Adob​​e 渐变选择器

javascript - 如何参数化模块,以便它可以按需配置需要它的应用程序?

c# - CaSTLe Windsor Ms Adapter Core 2.0 实现

javascript - 试图延迟 jquery 事件

javascript - 如何配置 Angular 2 路由器从/src 子文件夹运行

css - Angular 5中单独模块的单独样式

Angular:当使用 innerHTML 并禁用缓存时,图像会在单击时重新加载

asp.net - 谁能推荐一个用于 ASP.NET 2.0 Webforms 的 IoC 容器?