Ngx-Formly自定义类型传递自定义属性及方法调用问题
问题场景
我尝试创建一个Formly自定义类型,希望在字段定义中传递包含服务调用的自定义属性,字段配置代码如下:
{ key: 'city', type: 'customType', props: { label: 'Cities', }, field: { customProp3: inject(CityService).getCities, }, }
我通过扩展FormlyFieldConfig添加了field属性:
interface CustomFormlyFieldConfig extends FormlyFieldConfig { field?: { [additionalProperties: string]: any; }; }
初始问题
在自定义类型组件中访问field时得到的是空对象,请问正确访问该自定义属性的方式是什么?
更新问题
已通过this.field.field.customProp3在组件类中访问到了自定义属性,但调用该方法时出现this.httpClient未定义的问题。我期望该方法在服务上下文执行,却似乎是在组件类上下文执行,请问正确的调用方式是什么?
解决方案
1. 正确访问自定义属性
Formly内部会处理字段配置,直接扩展FormlyFieldConfig添加的field属性可能未被正确传递。更规范的做法是将自定义属性放到props中(Formly默认会传递props内所有属性到组件):
调整字段配置:
{ key: 'city', type: 'customType', props: { label: 'Cities', customProp3: inject(CityService).getCities, }, }
更新类型定义:
interface CustomFormlyProps extends FormlyFieldProps { customProp3?: () => Observable<any>; } interface CustomFormlyFieldConfig extends FormlyFieldConfig { props?: CustomFormlyProps; }
之后在组件中直接通过this.props.customProp3访问即可。
如果坚持使用自定义field属性,需确保通过Formly组件提供的field实例访问,即this.field['field']?.customProp3,但这种方式不符合Formly的常规用法,不推荐。
2. 修复方法调用上下文问题
传递inject(CityService).getCities时,方法的this上下文会丢失(脱离了CityService实例),导致调用时this.httpClient未定义。可通过以下两种方式解决:
方式一:绑定服务上下文
在字段配置中手动绑定this到服务实例:
const cityService = inject(CityService); { key: 'city', type: 'customType', props: { label: 'Cities', customProp3: cityService.getCities.bind(cityService), }, }
方式二:传递服务实例或包装成箭头函数
直接传递服务实例,在组件内调用方法:
{ key: 'city', type: 'customType', props: { label: 'Cities', cityService: inject(CityService), }, }
组件内调用:
this.props.cityService.getCities().subscribe(...);
或包装成箭头函数(箭头函数会继承当前inject上下文,自动绑定服务实例):
{ key: 'city', type: 'customType', props: { label: 'Cities', customProp3: () => inject(CityService).getCities(), }, }
内容的提问来源于stack exchange,提问作者Mario

