【问题标题】:How to make custom wrapper for 2 field groups with ngx-formly?如何使用 ngx-formly 为 2 个字段组制作自定义包装器?
【发布时间】:2026-02-05 16:20:04
【问题描述】:

我很困惑如何使用 ngx-formly 为我的表单进行布局。例如,我有 2 个字段组:General 和 Dynamic。

如何指定将军在一个 div 中,而在一个下拉列表(div)内的另一个 div 中动态?

官方示例如下: 包装器:

 <div class="card">
      <h3 class="card-header">{{ to.label }}</h3>
      <div class="card-body">
        <ng-container #fieldComponent></ng-container>
      </div>
    </div>

组件:

fields: FormlyFieldConfig[] = [
    {
      key: 'firstName',
      type: 'input',
      templateOptions: {
        required: true,
        type: 'text',
        label: 'First Name',
      },
    },
    {
      key: 'address',
      wrappers: ['panel'],
      templateOptions: { label: 'Address' },
      fieldGroup: [{
        key: 'town',
        type: 'input',
        templateOptions: {
          required: true,
          type: 'text',
          label: 'Town',
        },
      }],
    },
  ];

这里 &lt;ng-container #fieldComponent&gt;&lt;/ng-container&gt; 没有具体说明它是哪个字段

【问题讨论】:

    标签: angular forms ngx-formly


    【解决方案1】:

    只需将它们放在fieldGroup 中,然后使用自定义包装器或自定义类型来呈现dropdown-dev

    1. 使用自定义类型:https://stackblitz.com/edit/angular-u4hep4
    2. 使用自定义包装器:https://stackblitz.com/edit/angular-gjleoz

    注意:如果你想控制一个指定的字段,你可以使用自定义类型。

    【讨论】:

    • 在第一次 StackBlitz 中,文件 dropdown-dev.type.ts,第 8 行,我看到了 to.label。你能解释一下to 的来源吗?
    • @JamesPoulose tofield.templateOptions 的别名github.com/ngx-formly/ngx-formly/blob/v5/src/core/src/lib/…
    • @a.aitboudad 收到错误“无法绑定到 'ngForOf',因为它不是 'formly-field' 的已知属性”。
    • @aashirkhan 确保将 FormlyModule 和 CommonModule 导入到声明自定义类型/包装器的模块中。
    • 到目前为止,这可能与我的问题没有直接关系,但是这个答案和 cmets 告诉我 toformControl 等甚至可以在包装器中使用。非常感谢!