如何定义Formly自定义字段选项类型以通过Angular strictTemplates检查?
解决Angular strictTemplates下ngx-formly多选组件的类型校验问题
1. 自定义字段配置类型
扩展FieldTypeConfig,明确约束props.options为数组类型(可根据业务需求指定更具体的类型):
import { FieldTypeConfig } from '@ngx-formly/core'; // 若需要更严谨的类型,先定义选项接口 export interface SelectOption { label: string; value: string | number; } // 自定义配置类型,替换默认的props类型 export interface MultiselectFieldConfig extends FieldTypeConfig { props: { options: SelectOption[]; // 或直接用any[],根据需求选择 }; }
2. 更新组件的泛型类型
将组件继承的FieldType泛型从FieldTypeConfig改为自定义的MultiselectFieldConfig:
import { Component } from '@angular/core'; import { FieldType } from '@ngx-formly/core'; import { MultiselectFieldConfig } from './multiselect-field.config'; @Component({ selector: 'form-multiselect', templateUrl: 'multiselect.component.html', }) export class MultiselectComponent extends FieldType<MultiselectFieldConfig> { }
3. 清理模板中的类型转换
现在props.options的类型已明确匹配p-multiSelect的要求,直接移除$any即可:
<p-multiSelect [options]="props.options" [formControl]="formControl" [formlyAttributes]="field" />
这样就能通过strictTemplates的类型检查,同时保证类型约束的严谨性,避免使用$any绕过校验。
内容的提问来源于stack exchange,提问作者Rantiev
相关产品推荐
相关产品推荐

