angular - 有没有一种干净的方法将 addControl 与强类型表单一起使用?

标签 angular angular-forms

如果我有一个表格:

const form = new FormGroup({
  foo: new FormControl(''),
});

我想动态地添加一个控件,例如:

form.addControl('bar', new FormControl(''));

我收到一个错误,该错误似乎返回到 bar 未在 form 中定义。该错误建议将其添加为可选属性。 documentation还说:

In a strongly-typed group, the control must be in the group's type (possibly as an optional key).

看来我可以通过两种方式添加它:

  1. FormGroup 的泛型参数中显式指定完整的 Form 模型,其中包含可选的 bar 属性。我不想这样做,因为实际上它是一个庞大而复杂的对象。
const form = new FormGroup<{ foo: string, bar?: string }>({
  ...
});
  • bar 声明为 FormGroup 对象参数中的可选属性,但看起来我需要用它声明关联的 FormControl 值,这意味着它已经在表单中(我想在没有它的情况下开始)
  • const form = new FormGroup({
      foo: new FormControl(''),
      bar?: new FormControl('')
    });
    

    我需要添加一个实际上想要动态添加的 FormControl ,这似乎是矛盾的。

    有更好的方法吗?

    Stackblitz:https://stackblitz.com/edit/angular-xsu9at?file=src%2Fadd-control.ts

    最佳答案

    我对此进行了更多思考,从打字的 Angular 来看,您必须使用问题中给出的两种方法之一是有意义的 - 最终,表单模型的类型必须是已知的或可推断的,以满足表单模块的打字行为。

    来自 Angular 文档,FormRecord已添加作为 FormGroup 的替代品来处理这种情况:

    Some FormGroup usages do not fit the above pattern because the keys are not known ahead of time. The FormRecord class is designed for that case

    但是它有类型限制,这在我给出的示例中可以工作,因为这两个属性都是字符串,但在我的现实世界示例中它们是不同的。

    If you need a FormGroup that is both dynamic (open-ended) and heterogeneous (the controls are different types), no improved type safety is possible, and you should use UntypedFormGroup.

    另一种可能性是在初始声明中添加控件,但将其设置为禁用,这意味着它不会出现在 form.value 中:

     const form = new FormGroup({
        foo: new FormControl('foo'),
        bar: new FormControl({ value: 'bar', disabled: true }),
      });
    

    随后调用 form.controls.bar.enable() 而不是 form.addControl(..) 将导致 bar 出现在 form.value 中。

    Stackblitz 显示此内容:https://stackblitz.com/edit/angular-e58odo?file=src%2Fadd-control.ts,src%2Fmain.ts

    关于angular - 有没有一种干净的方法将 addControl 与强类型表单一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76180560/

    相关文章:

    javascript - 如果没有输入任何输入(包括 Angular 中的空格字符),如何禁用按钮

    Angular Material 对话框不需要的内联样式

    angular - 无法绑定(bind)到 'ngValue',因为它不是 'option' 的已知属性

    javascript - Angular 禁用按钮和垫输入错误消息

    angular - 加载动态响应表单,不等待http调用完成

    javascript - ng-repeat with form in angularjs

    Angular : How declare variable at Module and access it from all component?

    javascript - 文本区域的正则表达式

    angular - Angular 中的日期和货币验证 (4)

    angular - Angular 树组件的弹性高度虚拟滚动缺少树数据