【问题标题】:Angular formly: is there a way to set default options for all inputsAngular formly:有没有办法为所有输入设置默认选项
【发布时间】:2020-12-07 19:22:44
【问题描述】:

我有一个正式的表格,里面有很多 mat-inputs(是的,我正在使用 Material)。我希望他们每个人都有appearance=outline,因为我可以把它放在每个输入的templateOptions 中。但这不是 DRY。有没有办法在我的应用程序中为每个mat-input 设置默认appearance 并且不将其放在每个输入描述中?

UPD。我正在通过以下方式使用表单组件

<formly-form [form]="form" [fields]="fieldsDescription"></formly-form>

form 是通过循环(循环fieldsDescription 数组)和角度形式生成器生成的。 fieldsDescription 是从后端下载的。现在我在每个输入中输入appearance=outline。所以fieldsDescription 是一个对象数组,如下所示

{
    "key": "field_key",
    "type": "input",
    "templateOptions": {
        "label": "A label",
        "appearance": "outline",
        "placeholder": "",
        "required": true
    }
}

【问题讨论】:

标签: angular angular-material angular-formly ngx-formly


【解决方案1】:

为什么不将 MAT_FORM_FIELD_DEFAULT_OPTIONS {外观:'outline'}用作提供者?我想你想要你所有的输入外观大纲。在你的模块中

  providers: [
    { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'outline' } },
  ]

【讨论】:

    【解决方案2】:

    为什么不使用内部模板 &lt;mat-form-field appearance="outline"&gt; ?假设您在那里使用ngFor

    乐:

      fields: FormlyFieldConfig[] = [
        {
          key: 'Input',
          type: 'input',
          templateOptions: {
            label: 'Input',
            placeholder: 'Placeholder',
            description: 'Description',
            required: true,
            appearance: 'outline',
          },
        },
      ];
    

    对于 Formly,您可以使用 templateOptions 在表单字段配置中定义外观轮廓。来源here

    【讨论】:

    • 那不是我的情况。表单代码如下&lt;formly-form [form]="form" [fields]="fieldsDescription"&gt;&lt;/formly-form&gt;。表单是使用循环和表单构建器生成的,fieldsDescription 也是如此。但我不处理mat-form-field,它是在形式上完成的
    • 我找到了适合 Formly 的东西。答案已更新
    • 是的,我现在就是这样做的。我的问题是如何避免每次都写appearance: 'outline'。那不是干的。找不到任何形式的组件默认设置
    • 那么,我认为您需要提供更多代码。你的 formDescriptions 是如何组成的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多