Ngx-Formly how to pass custom properties to a custom type?

430 Views Asked by At

I'm trying to create a formly custom type. I want to be able to pass a custom property with the call to a service in the field definition. For example

{
  key: 'city',
  type: 'customType',
  props: {
    label: 'Cities',
  },
  field: {
    customProp3: inject(CityService).getCities,
  },
}

I have added the field property by extending FormlyFieldConfig as follows

interface CustomFormlyFieldConfig extends FormlyFieldConfig {
   field?: {
     [additionalProperties: string]: any;
   };
}

In the customType component I try to access field but I get an empty object

What is the correct way to access the properties of this custom property?

Update 0

In the component class I have managed to access the custom property using this.field.field.customProps. I try to invoke this method but when I try I get this.httpClient is undefined` I expect this call to be made in the context of the service but it seems to be trying to invoke the method in the context of the component class. Any ideas? What is the correct way to go about invoking this method?

2

There are 2 best solutions below

0
DaveExotic On

you can't call the inject method outside of the supported context (you can read about the supported context in the docs). A solution would be to inject the service inside of the custom component and call the method there.

0
Webia1 On

if it is a select box, you may not need a custom element, just use:

{
  key: 'cities',
  id: 'cities',
  type: 'select',
  props: {
    required: true,
    type: 'text',
    label: 'Cities',
    placeholder: 'e.g. Managua',
    options: this.defaultEntries, // to not display an empty list
  },
  expressionProperties: {
    'props.options': () => {
      return this.cityService.getCities(); // until you get them all
    },
  },
},