Angular formly: is there a way to set default options for all inputs

2.1k views Asked by At

I'm having a formly form with many mat-inputs (yes, I'm using Material) inside. I want each of them have appearance=outline of cause I can put it inside templateOptions of each input. But that's not DRY. Is there a way to set default appearance for each mat-input in my app and do not put it in each input description?

UPD. I'm using formly form component in the following way

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

form is generated with cycle (looping over fieldsDescription array) and angular form builder. fieldsDescription is downloaded from backend. Right now I put appearance=outline in each input. So fieldsDescription is an array of objects like the following

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

There are 3 answers

0
Eliseo On BEST ANSWER

why not use as provider MAT_FORM_FIELD_DEFAULT_OPTIONS { appearance: 'outline' }? I imagine you want all yours inputs apparence outline. In your module

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

why not using inside template <mat-form-field appearance="outline"> ? assuming you use an ngFor there.

le:

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

for Formly, you can use templateOptions to define appearance outline in your form fields configuration. source here

0
Webia1 On

If you want to change defaultOptions globally at once, you could try:

import { FormlyConfig } from '@ngx-formly/core';

constructor(private formlyConfig: FormlyConfig) {
  this.formlyConfig.setDefaultOptions({
    templateOptions: {
      appearance: 'outline',
    },
  });
}